简体   繁体   English

如何以编程方式更改Tkinter标签的颜色?

[英]How to change the color of a Tkinter label programmatically?

I am trying to change the color of a Tkinter label when ever the user clicks the check button. 我试图在用户点击检查按钮时更改Tkinter标签的颜色。 I am having trouble writing the function correctly and connecting that to the command parameter. 我无法正确编写函数并将其连接到命令参数。

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 谢谢

In your code, command=DarkenLabel is unable to find reference to the function DarkenLabel. 在您的代码中, command=DarkenLabel无法找到对DarkenLabel函数的引用。 Thus you need to define the function above that line, so you may use your code as following: 因此,您需要在该行上方定义函数,因此您可以使用以下代码:

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! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM