在Python3类的tkinter中创建多个按钮

2024-10-04 03:16:33 发布

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

我正在为一个项目创建的程序制作gui。我在同一行中制作了多个按钮,是否可以在一个类中这样做,这样我就不必重复代码?谢谢

flashcards.config(height = 15, width = 45 )
flashcards.place(x=1, y=600)

cMinigames = tk.Button(text="Core Minigames", bg="DarkSeaGreen1", fg="ghost white")
cMinigames.config(height = 15, width = 45)
cMinigames.place(x=300, y=600)

timetables = tk.Button(text="Timetables", bg="DarkSeaGreen1", fg="ghost white")
timetables.config(height = 15, width = 45 )
timetables.place(x=600, y=600)

quizzes = tk.Button(text="Quizzes", bg="DarkSeaGreen1", fg="ghost white")
quizzes.config(height = 15, width = 45 )
quizzes.place(x=900, y=600)

pmf = tk.Button(text="Pick My Focus!", bg="DarkSeaGreen1", fg="ghost white")
pmf.config(height = 15, width = 50 )
pmf.place(x=1200, y=600)```

Tags: textconfigplacebuttonwidthtkbgghost
1条回答
网友
1楼 · 发布于 2024-10-04 03:16:33

当然可以。有多种方法可以创建外观相似的按钮。其中一种方法是创建您提到的类

class MyButtons(tk.Button):
    def __init__(self,master,**kwargs):
        super().__init__(master =master, **kwargs)
        self.outlook = {"bg":"DarkSeaGreen1","fg":"ghost white","height":15,"width":45}
        self.config(self.outlook)

如果要更改按钮的背景色,只需更改self.outlook字典中的“bg”选项。您还可以向self.outlook字典添加其他配置选项

创建类后,需要使用该类创建按钮:

mybutton1 = MyButtons(root,text="Button 1")
mybutton1.place(x=100,y=100)

另一种创建类似按钮的方法是使用Ttk样式。这是另一种选择。你可能想看看这个

相关问题 更多 >