【问题标题】:Ideal way to config all the buttons of my Tkinter application at once?一次配置我的 Tkinter 应用程序的所有按钮的理想方式?
【发布时间】:2020-09-17 23:38:18
【问题描述】:

这是我的第一个 tkinter/gui 项目。我设置了一个 mvc 模式,并为我的应用程序的每个窗口都有一个视图类。
主窗口示例:

class ViewMain(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master, height = 300, width = 500)
        self.pack(fill='both', expand=True)
        self.BUTTON_SIZE = {'relheight' : 0.3, 'relwidth' : 0.35}
        self._set_widgets()
        self._set_layout()

    def _set_widgets(self):
        self.button = tk.Button(self, text = 'Text')

    def _set_layout(self):
        self.button.place(relx = 0.1, rely = 0.15, **self.BUTTON_SIZE)

目前,我有 6 个视图类,我想将按钮的浮雕更改为凹槽。因为我有 30 多个按钮,所以我想办法不要一直写以下内容:

self.button = tk.Button(self, text = 'Text', relief = 'groove')

如您所见,我的思路中的一个缺陷是我已经在使用重复的方法来配置按钮的大小。但让我们忽略这一点。
由于我对这一切还很陌生,我看到了三种方法:

  • 每次创建按钮时添加“relief = 'groove'”作为选项
  • 使用 ttk.Button 并配置样式。但是我必须为每个视图类执行此操作,并在每次创建按钮时添加样式
  • 为 tk.Button 编写一个包装器并改用它

最后一个选项让我想到了这个:

class CustomButton(tk.Button):
def __init__(self, master, text):
    super().__init__(master, text = text, relief = 'groove')

哪种方法可行,但我不能停止思考是否有更好的方法来解决这个问题?

【问题讨论】:

  • 我觉得CustomButton上课是个好办法。

标签: python tkinter configuration widget


【解决方案1】:

我没有测试它,但我的工作方式是这样的:

for widget in root.winfo_children():
    if isinstance(widget, tk.Button):
        widget.configure(relief = 'groove')

winfo_children() 为您提供所有小部件。 使用 if isinstance 检查小部件是否是 tkinter.Button 的实例。 如果是真的,您可以按照自己的喜好配置 Button。

我以前做过类似的事情,效果很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-21
    • 2020-11-29
    • 2012-11-29
    • 1970-01-01
    • 2019-07-07
    • 2016-04-20
    • 1970-01-01
    • 2011-01-25
    相关资源
    最近更新 更多