如何在Tkinter中动态更改按钮的背景颜色?
它仅在我初始化按钮时有效:
self.colorB = tk.Button(self.itemFrame, text="", bg="#234", width=10, command=self.pickColor)
我试过这个:
self.colorB.bg = "#234"
但它不起作用.. 感谢
答案 0 :(得分:5)
使用配置方法
self.colorB.configure(bg = "#234")
答案 1 :(得分:0)
在我生命中,仅使用configure方法就无法使其正常工作。 最终可行的方法是将所需的颜色(在我的情况下为按钮)设置为StringVar()(直接设置为get()),然后也使用按钮上的配置。
我为我最需要的用例写了一个非常普通的示例(很多按钮,需要引用它们(在Python 2和3中进行了测试):
Python 3:
import tkinter as tk
Python 2:
import Tkinter as tk
代码
root = tk.Tk()
parent = tk.Frame(root)
buttonNames = ['numberOne','numberTwo','happyButton']
buttonDic = {}
buttonColors = {}
def change_color(name):
buttonColors[name].set("red")
buttonDic[name].config(background=buttonColors[name].get())
for name in buttonNames:
buttonColors[name] = tk.StringVar()
buttonColors[name].set("blue")
buttonDic[name] = tk.Button(
parent,
text = name,
width = 20,
background = buttonColors[name].get(),
command= lambda passName=name: change_color(passName)
)
parent.grid(row=0,column=0)
for i,name in enumerate(buttonNames):
buttonDic[name].grid(row=i,column=0)
root.mainloop()