python单击后取消绑定/禁用键绑定,稍后再恢复 [英] python unbinding/disable key binding after click and resume it later

查看:67
本文介绍了python单击后取消绑定/禁用键绑定,稍后再恢复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to unbind/disable key once it's clicked, and resume its function after 2s. But I can't figure out the code for the unbinding. The bind is on window. Here's the code that I tried so far:

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"))

进一步,如何在2秒后重新启用密钥?

Further, how can I re-enable the key after 2s?

非常感谢您!

推荐答案

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

self.master.unbind('a', self.choiceA) does not work because the second argument you gave is the callback you want to unbind instead of the id returned when the binding was made.

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

In order to delay the re-binding, you need to use the .after(delay, callback) method where delay is in ms and callback is a function that does not take any argument.

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 ).

Remark: since you use a class, my bind_id global variable will be an attribute for you (self.bind_id).

这篇关于python单击后取消绑定/禁用键绑定,稍后再恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆