How can I dynamically change the color of a button in Tkinter?
How can I d开发者_运维技巧ynamically change the background color of a button in Tkinter ?
It only works when I initialize the button:
self.colorB = tk.Button(self.itemFrame, text="", bg="#234", width=10, command=self.pickColor)
I've tried this:
self.colorB.bg = "#234"
but it doesn't work.. thanks
Use the configure method
self.colorB.configure(bg = "#234")
For the life of me, I couldn't get it to work just using the configure method. What finally worked was setting the desired color (in my case, of a button) to a StringVar() (directly to the get()), and then using the config on the button too.
I wrote a very general example for the use case I need the most (which is a lot of buttons, where I need references to them (tested in Python 2 and 3):
Python 3:
import tkinter as tk
Python 2:
import Tkinter as tk
Code
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()
精彩评论