2014-10-20 123 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()