Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TkInter keypress, keyrelease events

Tags:

python

tkinter

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...
like image 910
lost Avatar asked Nov 30 '14 16:11

lost


Video Answer


2 Answers

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.

like image 111
lost Avatar answered Oct 11 '22 05:10

lost


Autorepeat behavior is system dependent. In Win7,

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

This is for less than a second.

like image 5
Terry Jan Reedy Avatar answered Oct 11 '22 05:10

Terry Jan Reedy