I am trying to import a keyboard listener into my class but keep getting a
NameError: name 'on_press' is not defined
Here is my code:
from pynput import keyboardclass game_code:with keyboard.Listener(on_press=on_press) as listener:listener.join()def check_key_press(self,key):try: k = key.charexcept: k = key.nameif k in ['up', 'down', 'left', 'right']:self.key = keys.append(k)return Trueelse:return False
Also not 100% sure on how with statements work.
Best Answer
I got it working using the format of their documentation online:
https://pythonhosted.org/pynput/keyboard.html
from pynput.keyboard import Key, Listenerdef on_press(key):#print('{0} pressed'.format(#key))check_key(key)def on_release(key):#print('{0} release'.format(# key))if key == Key.esc:# Stop listenerreturn Falsedef check_key(key):if key in [Key.up, Key.down, Key.left, Key.right]: print('YES')# Collect events until releasedwith Listener(on_press=on_press,on_release=on_release) as listener:listener.join()