一次配置Tkinter应用程序中所有按钮的理想方法? [英] Ideal way to config all the buttons of my Tkinter application at once?

查看:63
本文介绍了一次配置Tkinter应用程序中所有按钮的理想方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is my first tkinter/gui project. I set up a mvc pattern and have a view class for each window of my application.
An example for the main window:

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多个按钮,所以我一直在寻找一种不写以下内容的方法:

Currently, I have 6 view classes and I want to change the relief of the buttons to groove. As I have 30+ buttons, I look for a way to not write the following all the time:

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

如您所见,我思路的一个缺陷是我已经在使用重复的方法来配置按钮的大小.但是,我们就忽略它.
由于我对所有这些都还比较陌生,因此我看到了三种实现方法:

As you can see, one flaw in my train of thought is that I'm already using a repetitive approach to configure the size of the buttons. But let's just ignore that.
As I'm fairly new to all of this, I see three ways of doing this:

  • 每次创建按钮时,都将"relief ='groove'"添加为选项
  • 使用ttk.Button并配置样式.但是我必须为每个视图类都这样做,并且每次创建按钮时都要添加样式
  • 为tk.Button编写包装,并使用该包装

最后一个选择使我想到了这一点:

The last option led me to this:

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

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

Which works but I cannot stop thinking if there is a better way to approach this?

推荐答案

我没有测试它,但是我的解决方法是这样的:

I didn't test it but the way I would work around is like this:

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

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

the winfo_children() gives you all widgets. With if isinstance you checking if the widget is an instance of tkinter.Button. If it's true you configure the Button how you like.

我以前做过类似的事情,而且效果很好.

I did something like this before and it worked fine.

这篇关于一次配置Tkinter应用程序中所有按钮的理想方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆