简体   繁体   English

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

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

So,the problem is that I have dozens of buttons with same configuration and i want to shorten it so that I dont need to write same config to each button.所以,问题是我有几十个具有相同配置的按钮,我想缩短它,这样我就不需要为每个按钮编写相同的配置。

Here is example of code:这是代码示例:

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

As you can see many elements of configure() are the same, and I know it can be shorter but I don't have any idea on how to do that.如您所见,configure() 的许多元素都是相同的,而且我知道它可以更短,但我不知道如何做到这一点。 Can you help me?你能帮助我吗?

You can define a Style and then apply it to your buttons.您可以定义一个Style ,然后将其应用到您的按钮。

Here's some examples from the documentation using Tk themed widgets :以下是使用Tk 主题小部件文档中的一些示例:

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

Second example:第二个例子:

# 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM