2014-10-20 147 views
1

我想使用按鍵事件爲我的GUI創建一個函數。我的目標是允許在用戶按下空格鍵1秒以上時調用函數,如果在此1秒內釋放,則中止函數。Python Tkinter:在長按空格鍵1秒後調用函數

我該怎麼做?

隨意編輯自己的例子:

from Tkinter import Tk, Frame 

class Application(Frame): 

    def __init__(self, parent): 
     Frame.__init__(self, parent) 
     self.parent = parent 
     self.parent.geometry('%dx%d+%d+%d' % (800, 300, 0, 0)) 
     self.parent.resizable(0, 0) 

     self.pack(expand = True) 
     self.parent.bind('<Control-s>', self.printer) 
    def printer(self, event = None): 
     print "Hello World" 

def main(): 
    root = Tk() 
    Application(root) 
    root.mainloop() 

if __name__ == '__main__': 
    main() 

的Python 2.7,Linux的

參考:http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

回答

3

這或者會是很容易的,否則真的很難。它取決於幾個因素。從概念上講,解決方法很簡單:

  1. 的空格鍵被按下的使用after安排一個工作,在未來
  2. 在關鍵的發佈運行,取消作業。

如果遇到困難,某些系統會在您按下某個按鍵時繼續自動重複按鍵(因此您將在一行中獲得一連串的按鍵,而無需釋放)或者一對印刷機和版本(您將獲得穩定的新聞/發佈活動)。這可能在鍵盤硬件級別完成,也可能由操作系統完成。

+0

bind(「」)檢查是否按下空格鍵,它的釋放如何? – 2014-10-22 15:28:55

+2

你可以使用''(和'KeyPress-space',如果你想成爲書呆子) – 2014-10-22 15:35:44

+0

我編輯了我的問題了解更多細節。如果它在1秒鐘內,我想中止函數的釋放。 – 2014-10-22 17:00:28

0

我知道這是一個古老的問題,但是我能夠實施一個有點反覆試驗的解決方案,並且認爲我會將它發佈到這裏以防別人幫助其他人。 (請注意,我只用Python 3.6和Windows進行了測試,但是我有一個類似的解決方案,在Linux上使用長按鈕進行操作,所以我假設這是傳輸)。

from tkinter import Tk, Frame 

class Application(Frame): 
    def __init__(self, parent): 
     super().__init__(parent) 
     self.parent = parent 
     self.parent.geometry('%dx%d+%d+%d' % (800, 300, 0, 0)) 
     self.parent.resizable(0, 0) 

     self.pack(expand = True) 
     self._short_press = None 
     self.parent.bind('<KeyPress-space>', self.on_press_space) 
     self.parent.bind('<KeyRelease-space>', self.on_release_space) 

    # set timer for long press 
    def on_press_space(self, event): 
     if self._short_press is None: # only set timer if a key press is not ongoing 
      self._short_press = True 
      self._do_space_longpress = self.after(1000, self.do_space_longpress) 

    # if it was a short press, cancel event. If it was a long press, event already happened 
    def on_release_space(self, event): 
     if self._short_press: 
      self.cancel_do_space_longpress() 

    # do long press action 
    def do_space_longpress(self): 
     self.cancel_do_space_longpress() # cancel any outstanding timers, if they exist 
     print('long press') 

    # cancels long press events 
    def cancel_do_space_longpress(self): 
     self._short_press = None 
     if self._do_space_longpress: 
      self.parent.after_cancel(self._do_space_longpress) 

def main(): 
    root = Tk() 
    Application(root) 
    root.mainloop() 

if __name__ == '__main__': 
    main()