【问题标题】:Creating multiple buttons in tkinter in a class - python 3在类中的 tkinter 中创建多个按钮 - python 3
【发布时间】:2021-01-16 00:12:12
【问题描述】:

我正在为我正在为项目创建的程序制作 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)```

【问题讨论】:

  • for i in range(x):tk.Button().pack()

标签: python python-3.x oop tkinter


【解决方案1】:

是的,当然可以。有多种方法可以创建看起来相似的按钮。一种方法是创建您提到的类。

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 样式。那是另一种选择。你可能想看看那个。

【讨论】:

  • 非常感谢!
  • init前的“super()”有什么作用?
  • 它与继承有关。基本上我对 super 所做的事情相当于 tk.Button.__init__(self,**kwargs)。我正在初始化 tk.Button 类的实例。这是关于 OOP 而不是 tkinter。如果您觉得需要更多信息,可以查看programiz.com/python-programming/methods/built-in/super 和一般的 OOP。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
相关资源
最近更新 更多