TkInter keypress, keyrelease events

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

I understood that the Tk keypress and keyrelease events were supposed only to fire when the key was actually pressed or released?

However with the following simple code, if I hold down the "a" key I get a continual sequence of alternating keypress/keyrelease events.

Am I doing something wrong or is TkInter buggy? This is Python2.7 on Linux mint.

from Tkinter import * def keyup(e):     print 'up', e.char def keydown(e):     print 'down', e.char  root = Tk() frame = Frame(root, width=100, height=100) frame.bind("<KeyPress>", keydown) frame.bind("<KeyRelease>", keyup) frame.pack() frame.focus_set() root.mainloop() 

Output when pressing and holding "a":

down a up a down a up a down a up a down a up a etc... 

回答1:

Ok some more research found this helpful post which shows this is occuring because of X's autorepeat behaviour. You can disable this by using

os.system('xset r off') 

and then reset it using "on" at the end of your script. The problem is this is global behaviour - not just my script - which isn't great so I'm hoping someone can come up with a better way.



回答2:

Autorepeat behavior is system dependent. In Win7,

down a down a down a ... down a up a 

This is for less than a second.



回答3:

how about;

from Tkinter import *  wn = Tk() wn.title('KeyDetect')  m = 0  def down(e):     if m == 0:         print 'Down\n', e.char, '\n', e         global m         m = 1  def up(e):     if m == 1:         print 'Up\n', e.char, '\n', e         global m         m = 0  wn.bind('<KeyPress>', down) wn.bind('<KeyRelease>', up)  wn.mainloop() 

now it won't repeat.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!