How to get keycode in Python using Tkinter or PyGame
Tkitner
This code uses tkinter
to get pressed/released key and display its keycode (scancode), keysym, char (unicode)
import tkinter as tk
# --- functions ---
def on_press(event):
# display pressed key
#print(event)
print('PRESS | keycode: {}, keysym: {}, char: {}'.format(event.keycode, event.keysym, event.char))
def on_release(event):
# display released key
#print(event)
print('RELEASE | keycode: {}, keysym: {}, char: {}'.format(event.keycode, event.keysym, event.char))
# exit program on ESC
#if event.keysym == 'Escape':
# root.destroy()
# --- main ---
root = tk.Tk()
# assign functions to events
root.bind('<KeyPress>', on_press)
root.bind('<KeyRelease>', on_release)
root.mainloop()
Result
PRESS | keycode: 38, keysym: a, char: a
RELEASE | keycode: 38, keysym: a, char:
PRESS | keycode: 54, keysym: c, char: c
RELEASE | keycode: 54, keysym: c, char:
PRESS | keycode: 12, keysym: 3, char: 3
RELEASE | keycode: 12, keysym: 3, char:
PRESS | keycode: 50, keysym: Shift_L, char:
PRESS | keycode: 13, keysym: dollar, char: $
RELEASE | keycode: 13, keysym: dollar, char:
RELEASE | keycode: 50, keysym: Shift_L, char:
PRESS | keycode: 50, keysym: Shift_L, char:
PRESS | keycode: 10, keysym: exclam, char: !
RELEASE | keycode: 10, keysym: exclam, char:
RELEASE | keycode: 50, keysym: Shift_L, char:
PyGame
This code uses pygame
to get pressed/released key and display its scancode (keycode), key, unicode (char)
import pygame
# init pygame and create window which will be get events from system
pygame.init()
screen = pygame.display.set_mode((800,600))
running = True
while running:
for event in pygame.event.get():
# close window with button [X]
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
# display pressed key
#print(event)
print('PRESS | scancode: {}, key: {}, unicode: {}'.format(event.scancode, event.key, event.unicode))
elif event.type == pygame.KEYUP:
# display released key
#print(event)
print('RELEASE | scancode: {}, key: {}'.format(event.scancode, event.key)) # `KEYUP` doesn't have `event.unicode`
# exit on ESC
#if event.key == pygame.K_ESCAPE:
# running = False
# exit
pygame.quit()
Result
PRESS | scancode: 38, key: 97, unicode: a
RELEASE | scancode: 38, key: 97
PRESS | scancode: 54, key: 99, unicode: c
RELEASE | scancode: 54, key: 99
PRESS | scancode: 50, key: 304, unicode:
PRESS | scancode: 13, key: 52, unicode: $
RELEASE | scancode: 13, key: 52
RELEASE | scancode: 50, key: 304
PRESS | scancode: 50, key: 304, unicode:
PRESS | scancode: 10, key: 49, unicode: !
RELEASE | scancode: 10, key: 49
RELEASE | scancode: 50, key: 304
If you like it
Buy a Coffee
