【问题标题】:Make the button enabled when text is entered in Entry widget on Tkinter在 Tkinter 的 Entry 小部件中输入文本时启用按钮
【发布时间】:2021-07-04 13:10:24
【问题描述】:

所以我试图在使用 tkinter 在条目小部件中输入文本时启用按钮,但是我不认为它可以工作。 我的代码是:

def capture():
    if e.get():
        button['state'] = 'normal'

e = Entry(root, font = 20,borderwidth=5,command = capture)
e.pack()

但是我知道 Entry 小部件没有称为命令的参数。

【问题讨论】:

    标签: python tkinter-entry


    【解决方案1】:

    实现此目的的方法之一是使用StringVar

    def capture(*args):
        if e.get():
            button['state'] = 'normal'
        else:
            button['state'] = 'disabled'
    
    var = StringVar()
    e = Entry(root, font = 20,borderwidth=5,textvariable=var)
    e.pack()
    
    var.trace('w',capture)
    

    trace() 将在每次var 的值发生变化时调用提供的回调。

    第二种方式是使用bind

    def capture():
        if e.get():
            button['state'] = 'normal'
        else:
            button['state'] = 'disabled'
    
    e = Entry(root, font = 20,borderwidth=5)
    e.pack()
    e.bind('<KeyRelease>',lambda e: capture()) # Bind keyrelease to the function
    

    使用bind,每次释放键时都会调用函数,无论键是什么。这可能会好一些,因为您创建StringVar 并不是为了使用它的trace

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 2013-04-28
      • 2022-01-11
      • 2022-11-04
      相关资源
      最近更新 更多