Python 如何以编程方式更改 Tkinter 标签的颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42942534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the color of a Tkinter label programmatically?
提问by Sean W
I am trying to change the color of a Tkinter label when ever the user clicks the check button. I am having trouble writing the function correctly and connecting that to the command parameter.
每当用户单击复选按钮时,我都会尝试更改 Tkinter 标签的颜色。我无法正确编写函数并将其连接到命令参数。
Here is my code:
这是我的代码:
import Tkinter as tk
root = tk.Tk()
app = tk.Frame(root)
app.pack()
label = tk.Label(app, bg="white", pady=5, font=(None, 1), height=20, width=720)
checkbox = tk.Checkbutton(app, bg="white", command=DarkenLabel)
label.grid(row=0, column=0, sticky="ew")
checkbox.grid(row=0, column=0, sticky="w")
def DarkenLabel():
label.config(bg="gray")
root.mainloop()
Thank you
谢谢
回答by abhinav
In your code, command=DarkenLabel
is unable to find reference to the function DarkenLabel. Thus you need to define the function above that line, so you may use your code as following:
在您的代码中,command=DarkenLabel
找不到对函数 DarkenLabel 的引用。因此,您需要在该行上方定义函数,因此您可以使用以下代码:
import Tkinter as tk
def DarkenLabel():
label.config(bg="gray")
root = tk.Tk()
app = tk.Frame(root)
app.pack()
label = tk.Label(app, bg="white", pady=5, font=(None, 1), height=20, width=720)
checkbox = tk.Checkbutton(app, bg="white", command=DarkenLabel)
label.grid(row=0, column=0, sticky="ew")
checkbox.grid(row=0, column=0, sticky="w")
root.mainloop()
Hope it helps!
希望能帮助到你!