[英]How can I dynamically change the color of a button in Tkinter?
How can I dynamically change the background color of a button in Tkinter ? 如何在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 但这不起作用..谢谢
使用配置方法
self.colorB.configure(bg = "#234")
For the life of me, I couldn't get it to work just using the configure method. 对于我一生,仅使用configure方法就无法使其正常工作。 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. 最终可行的方法是将所需的颜色(在我的情况下为按钮)设置为StringVar()(直接设置为get()),然后也使用按钮上的配置。
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 2和3中进行了测试):
Python 3: Python 3:
import tkinter as tk
Python 2: 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.