2017-03-22 83 views
3

我试图在用户单击检查按钮时更改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() 

谢谢

+0

它工作正常,你只需要在你使用它作为命令变量的位置之前移动'DarkenLabel'函数。你看到它运行失败或者在运行脚本时遇到异常? –

+0

真的那么简单! –

回答

5

在你的代码,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() 

希望它有帮助!

+0

那么,我寻求这样一个很酷和简单的解决方案,并编写了许多不同的想法,包括ttk等等,我在那里编辑了一个标签,'救济'不再有效......但是,你的提示使我的晚上。 Thx +1 – Semo

相关问题