pythontkintercross-platformkeyrelease

tkinter <KeyRelease> different behavior on Windows and Linux


In my CS class, my students just finished their first "clone your classic" contest. The PONG team went rapidly through the "Hey my paddle is frozen" issue with their two players on one keyboard version. I came across this problem 5 years ago and found Python bind - allow multiple keys to be pressed simultaniously that enlightened me (watch out ! The article uses python2.7). But I didn't realize then that the script only worked on windows machines.

On a linux system, the <KeyRelease-a> event triggers the callback, but the event.char then points to ' ' and not 'a' as one could expect. I tried googling the issue, but even on stackoverflow I couldn't find anything of interest.

Any hints? Next find the reproducible code sample:

import os
from tkinter import *

os.system("xset r off")

def keyup(e):
    #print(f"up {e.char}")
    print(f"up {e.keysym}")

def keydown(e):
    #print(f"down {e.char}")
    print(f"down {e.keysym}")

root = Tk()
frame = Frame(root, width=100, height=100)
frame.bind("<KeyPress>", keydown)
frame.bind("<KeyRelease>", keyup)
frame.pack()
frame.focus_set()
root.mainloop()

os.system("xset r on")

for reproducibility as asked by Bryan, which I thank for his concern about my question.


Solution

  • Just to close the subject, all the job has been done by Atlas435 : if you want to code a Pong with Tkinter, with two paddles listening independently to the keystrokes, follow this post Python bind - allow multiple keys to be pressed simultaniously but change e.char into e.keysym in the callbacks to get which key triggered the event Pressed or Released.