如何在tkinter ttk.button中使用不同的颜色给按钮着色?

4
我想给按钮着色,但目前我只能找到一次性着色所有按钮的方法。
我尝试在 ttk.button() 中使用 bg = "red",但是它返回以下错误:

/ _ tkinter.TclError: unknown option "-bg"

style = ttk.Style()
style.configure("TButton",foreground="red")

#Botoes para funcoes da treeview
ttk.Button (text='Deletar', command = self.delete).grid(row=5,column=0, sticky = W + E)
ttk.Button (text='Editar', command = self.editar).grid(row=5,column=1, sticky = W + E)

我希望你能帮助我,我会非常感激。

1个回答

4
您不能在ttk.Style()中使用bgfg作为backgroundforeground的简写形式,必须使用完整单词backgroundforeground来配置样式。

tkinter.TclError: 未知选项“-bg”

您遇到此错误是因为您无法将-bg作为参数传递给ttk.Button()。要配置任何ttk小部件的样式,您必须使用其相应的样式名称,例如Button:“TButton”,Label:“TLabel”,Frame:“TFrame”等等,请参见Tk主题小部件的文档
如果要为不同的按钮创建单独的样式,则可以创建自定义样式名称。
例如:
from tkinter import *
from tkinter import ttk

root = Tk()

button1_style = ttk.Style() # style for button1
# Configure the style of the button here (foreground, background, font, ..)
button1_style.configure('B1.TButton', foreground='red', background='blue')
button1 = ttk.Button(text='Deletar', style='B1.TButton')
button1.pack()

button2_style = ttk.Style() # style for button2
# Configure the style of the button here (foreground, background, font, ..)
button2_style.configure('B2.TButton', foreground='blue', background='red')
button2 = ttk.Button(text='Editar', style='B2.TButton')
button2.pack()

root.mainloop()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接