【问题标题】:How to change the color of a Tkinter label programmatically?如何以编程方式更改 Tkinter 标签的颜色?
【发布时间】:2017-08-14 00:42:11
【问题描述】:

每当用户单击检查按钮时,我都会尝试更改 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()

谢谢

【问题讨论】:

  • 它工作正常,您只需将DarkenLabel 函数移动到将其用作命令变量的位置。您是否看到它无法正常工作或在运行脚本时遇到异常?
  • 真的就这么简单!

标签: python tkinter


【解决方案1】:

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

希望对你有帮助!

【讨论】:

  • 好吧,我寻求了这样一个很酷且简单的解决方案,并编写了许多不同的想法,包括 ttk 等等,我在其中编辑了一个“救济”不再起作用的标签......但是你的小费度过了我的夜晚。谢谢+1
  • 谢谢!你今天帮助了我的学生!
猜你喜欢
  • 2017-08-02
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 2022-08-22
  • 2015-12-06
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多