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

Sea*_*n W 6 python tkinter

我试图在用户点击检查按钮时更改Tkinter标签的颜色.我无法正确编写函数并将其连接到命令参数.

这是我的代码:

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()
Run Code Online (Sandbox Code Playgroud)

谢谢

abh*_*nav 8

在您的代码中,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()
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!