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

时间:2017-03-22 04:02:06

标签: 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()

谢谢

1 个答案:

答案 0 :(得分: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()

希望它有所帮助!

相关问题