Ideal way to config all the buttons of my Tkinter application at once?

与世无争的帅哥 提交于 2021-01-28 10:51:40

问题


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)

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:

  • Add "relief = 'groove'" as an option every time I create a button
  • Use a ttk.Button and config the style. But I'd have to do this for every view class and add the style every time I create a button as well
  • Write a wrapper for the tk.Button and use that instead

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?


回答1:


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')

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.



来源:https://stackoverflow.com/questions/62102253/ideal-way-to-config-all-the-buttons-of-my-tkinter-application-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!