python - 在类中的 tkinter 中创建多个按钮 - python 3
问题描述
我正在为我正在为项目创建的程序制作 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)```
解决方案
是的,当然可以。有多种方法可以创建看起来相似的按钮。一种方法是创建您提到的类。
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 样式。那是另一种选择。你可能想看看那个。
推荐阅读
- angularjs - 在 angularjs 中观看模板
- java - 嵌套循环将数据添加到数组
- powershell - 从 C++ 应用程序发送的 Powershell 电子邮件
- microsoft-graph-api - Graph API - 无法使用有效的访问令牌上传文件
- php - MySQL:如何根据另一个表中的信息从表中进行选择?
- python - 如何从数据框上的地图函数返回值
- ios - IPFS IONIC iOS:如何删除数据存储级别的锁定文件?
- amazon-web-services - AWS StepFunction:获取错误为“错误”:“KeyError”
- gcc - 如何在 gimple 中找到自由操作?
- ruby-on-rails - 一些资产没有加载到旧的 Rails 3-2-stable 应用程序中