I am trying to capture in python if the user pressed the Alt Gr but every time when the user press the Alt_Gr the system see that the user also pressed the Left CTRL.
I want to catch and make difference if the user pressed the Alt_Gr or/amd the Left CTRL, my code:
from pynput import keyboard
# Set to track if Alt Gr is pressed
alt_gr_pressed = False
def on_press(key):
global alt_gr_pressed
if key == keyboard.Key.alt_gr:
alt_gr_pressed = True
print(f'Special key {key} pressed')
elif key == keyboard.Key.ctrl_l and alt_gr_pressed:
# Ignore Ctrl_L if Alt Gr is pressed
return
else:
try:
print(f'Key {key.char} pressed')
except AttributeError:
print(f'Special key {key} pressed')
def on_release(key):
global alt_gr_pressed
if key == keyboard.Key.alt_gr:
alt_gr_pressed = False
print(f'Key {key} released')
if key == keyboard.Key.esc: # Stop listener
return False
# Collect events until released
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()`
Thank you!
New contributor
Tom Tall is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2