【问题标题】:Check state of button in tkinter检查 tkinter 中按钮的状态
【发布时间】:2017-03-08 01:35:09
【问题描述】:

在 tkinter GUI 上,我想根据悬停按钮的状态在画布上打印不同的消息。如果按钮本身被禁用,我想在画布上显示另一条消息,而不是按钮为正常时。 我有这个(剥离的)相关代码:

from tkinter import *

class app:
    def __init__(self):
        self.window = Tk()
        self.button = Button(self.window,text="Button",command=self.someCommand,state=DISABLED)

        self.button.bind("<Enter>", self.showText)
        self.button.bind("<Leave>", self.hideText)

        self.window.mainloop()

    def showText(self):
        if self.button["state"] == DISABLED:
            #print this text on a canvas
        else:
            #print that text on a canvas

    def hideText(self):
        #remove text    

def main()
    instance = app()

main()

这总是在画布上绘制“那个文本”,而不是“这个文本”

我也尝试过以下方法:

 self.button['state']
 == 'disabled'
 == 'DISABLED'

如果我打印:

print(self.button["state"] == DISABLED)

它给了我:

False

改变状态使用:

self.button["state"] = NORMAL

按我的预期工作。

我在这里阅读了一些主题,但似乎没有一个能回答为什么 if 语句不起作用的问题。

【问题讨论】:

    标签: python button canvas tkinter bind


    【解决方案1】:

    经过更多研究,我终于找到了解决方案。

    print(self.button['state'])
    

    打印:

    disabled
    

    所以我可以使用:

    state = str(self.button['state'])
    if state == 'disabled':
        #print the correct text!
    

    【讨论】:

    • 超级简单的方法!谢谢你,为我节省了很多时间
    • 注意:self.button['state'] 不返回字符串。相反,它返回&lt;class '_tkinter.Tcl_Obj'&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 2018-07-27
    • 2019-09-27
    相关资源
    最近更新 更多