【问题标题】:python unbinding/disable key binding after click and resume it later单击后python取消绑定/禁用键绑定并稍后恢复
【发布时间】:2023-03-18 19:45:01
【问题描述】:

我正在尝试在单击后取消绑定/禁用键,并在 2 秒后恢复其功能。但我无法弄清楚解除绑定的代码。绑定在窗口上。这是我到目前为止尝试过的代码:

self.choiceA = self.master.bind('a', self.run1) #bind key "a" to run1
def run1(self, event=None):
    self.draw_confirmation_button1()
    self.master.unbind('a', self.choiceA) #try1: use "unbind", doesn't work

    self.choiceA.configure(state='disabled') #try2: use state='disabled', doesn't't work, I assume it only works for button
    self.master.after(2000, lambda:self.choiceA.configure(state="normal"))

另外,如何在 2s 后重新启用密钥?

非常感谢!

【问题讨论】:

    标签: python events tkinter bind unbind


    【解决方案1】:

    self.master.unbind('a', self.choiceA) 不起作用,因为您提供的第二个参数是您要取消绑定的回调,而不是绑定时返回的 id。

    为了延迟重新绑定,您需要使用.after(delay, callback) 方法,其中delay 以ms 为单位,callback 是不带任何参数的函数。

    import tkinter as tk
    
    def callback(event):
        print("Disable binding for 2s")
        root.unbind("<a>", bind_id)
        root.after(2000, rebind)  # wait for 2000 ms and rebind key a
    
    def rebind():
        global bind_id
        bind_id = root.bind("<a>", callback)
        print("Bindind on")
    
    
    root = tk.Tk()
    # store the binding id to be able to unbind it
    bind_id = root.bind("<a>", callback)
    
    root.mainloop()
    

    备注:既然你使用了一个类,我的bind_id全局变量将是你的一个属性(self.bind_id)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 2010-10-05
      • 1970-01-01
      • 2014-09-04
      • 2012-01-11
      • 1970-01-01
      相关资源
      最近更新 更多