[TKinter]创建多个具有相同 configure() 属性的按钮

[TKinter]Create multiple buttons with same configure() atributes

所以,问题是我有几十个具有相同配置的按钮,我想缩短它,这样我就不需要为每个按钮编写相同的配置。

代码示例如下:

  self.Button1 = tk.Button(self.ButtonsFrame1)
  self.Button1.place(relx=0.664, rely=0.275, height=40, width=94)
  self.Button1.configure(activebackground="beige",
                              activeforeground="#000000",
                              background="#8c9eef",
                              compound='left',
                              foreground="#000000",
                              highlightbackground="#d9d9d9",
                              highlightcolor="black",
                              pady="0",
                              text='''button1''')

  self.Button2 = tk.Button(self.ButtonsFrame2)
  self.Button2.place(relx=0.824, rely=0.275, height=40, width=94)
  self.Button2.configure(activebackground="beige",
                                activeforeground="#000000",
                                background="#8c9eef",
                                compound='left',
                                foreground="#000000",
                                highlightbackground="#d9d9d9",
                                highlightcolor="black",
                                pady="0",
                                text='''button2''')

如您所见,configure() 的许多元素都是相同的,我知道它可以更短,但我不知道如何做到这一点。你能帮帮我吗?

您可以定义一个 Style,然后将其应用于您的按钮。

以下是 documentation using Tk themed widgets 中的一些示例:

from tkinter import ttk
# change default style for every button 
ttk.Style().configure("TButton", padding=6, relief="flat", background="#ccc")
btn = ttk.Button(text="Sample")

第二个例子:

# override the basic Tk widgets
from tkinter import *
from tkinter.ttk import *

style = Style()
style.configure("my.TButton", activebackground="beige",
                              activeforeground="#000000",
                              background="#8c9eef",
                              compound='left',
                              foreground="#000000",
                              highlightbackground="#d9d9d9",
                              highlightcolor="black",
                              pady="0")
btn1 = Button(style="my.TButton", text="button1")
btn2 = Button(style="my.TButton", text="button2")