2017-02-13 55 views
0

我試圖解除/禁用鍵一旦點擊,並恢復其功能後2s。但我無法弄清楚解除綁定的代碼。綁定在窗口上。這裏是我到目前爲止的代碼:蟒蛇解除綁定/禁用鍵綁定後點擊並稍後恢復它

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秒後重新啓用密鑰?

非常感謝!

回答

0

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)的屬性。