如何在pythontkinter中创建一个小部件设计?

2024-05-16 20:36:34 发布

您现在位置:Python中文网/ 问答频道 /正文

如您所见,字体(名称、大小、样式等)在每个Checkbutton中都是重复的。我怎样才能为它们创建一个单独的设计,而不是在每个Checkbutton中重复相同的代码?谢谢

main.iconify()
    global motor_wire
    motor_wire = Toplevel(main)


motorframe = LabelFrame(motor_wire, text="SIZE OF WIRE", font = ('Garamond', '25', 'bold', 'underline'), padx = 270, pady = 167, bd = 8)
motorframe.place(x = 30, y = 5)
Label(motorframe).pack()

thirteen = Checkbutton(motor_wire, text = '#13',font=("Calibri", '30', 'bold'), relief = 'groove' ,
                       bd = 5,padx = 0, pady = 5).place(x = 52, y = 50)
fourteen = Checkbutton(motor_wire, text = '#14',font=("Calibri", '30', 'bold'),relief = 'groove' ,
                       bd = 5,padx = 0, pady = 5).place(x = 189, y = 50)
fifteen = Checkbutton(motor_wire, text = '#15',font=("Calibri", '30','bold'),relief = 'groove' ,
                        bd = 5, padx = 0, pady = 5).place(x = 326, y = 50)

Tags: textmainplacebdfontboldwiremotor
1条回答
网友
1楼 · 发布于 2024-05-16 20:36:34

只需创建重复属性的字典:

d = dict(font=("Calibri", '30', 'bold'), relief='groove', bd=5, padx=0, pady=5)

然后将其解包到构造函数中:

thirteen = Checkbutton(motor_wire, text='#13', **d)

请记住不要链接放置方法,否则以后将无法再引用小部件:

thirteen.place(x=52, y=50)

还可以考虑为这些复选按钮使用一个列表,这样就可以在循环中创建thirteenfourteen等(可能也是从onezero):

buttons = []
for i in range(15):
    buttons.append(Checkbutton(motor_wire, text=f'#{i}', **d))
# manual placement with .place() afterward, or maybe check out .grid()

相关问题 更多 >