【问题标题】:Getting the value of the bg property of a Label in Tkinter在 Tkinter 中获取 Label 的 bg 属性的值
【发布时间】:2015-03-11 16:51:12
【问题描述】:

我一直在使用 Tkinter 学习 ui 编程,并且已经取得了相当大的进展。我可以配置/更改标签的文本、fgbg 属性,但我不知道如何获取Labelbg 属性。

有什么方法可以将 Tkinter 标签的 bg 值保存到变量中,以便与其他值进行比较?

【问题讨论】:

  • 谢谢,我很感激。我现在无法访问我的电脑,但我会在我访问时尝试。
  • 我把我的评论变成了一个完整的答案。并且不小心删除了我的评论。

标签: python tkinter label


【解决方案1】:

你可以使用cget():

label.cget('background')

或者您可以将标签视为字典:

label['background']

例子:

from Tkinter import *

main = Tk()
l = Label(main, text = "Label", background = "lime")
l.pack()

if l["background"] == 'lime':
    print "Lime!"
if l.cget("background") == 'lime':
    print "Still Lime!"

main.mainloop()

控制台输出:

Lime!
Still Lime!

【讨论】:

  • 哦,我忘了小部件支持直接索引。好吧,你赢了:-)
  • 是的,cget() 很好,但我认为直接索引更“pythonic”。
【解决方案2】:

您可以使用cget 方法来获取小部件属性的值。示例:

if my_widget.cget("background") == "red":
    print "The widget is red"

【讨论】:

  • 谢谢!这会有所帮助。有 2 个答案,我会同时检查它们,但我只能检查 1。机器人回答对我有帮助。
猜你喜欢
  • 2022-11-10
  • 2020-10-02
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多