Gary I
Gary I

Reputation: 55

Keyboard Listener from pynput

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 keyboard
class game_code:

    with keyboard.Listener(on_press=on_press) as listener:
        listener.join()

    def check_key_press(self,key):
       try: k = key.char
       except: k = key.name

       if k in ['up', 'down', 'left', 'right']:
          self.key = keys.append(k)
          return True

        else:
          return False

Also not 100% sure on how with statements work.

Upvotes: 2

Views: 24914

Answers (1)

clearshot66
clearshot66

Reputation: 2302

I got it working using the format of their documentation online:

https://pythonhosted.org/pynput/keyboard.html

from pynput.keyboard import Key, Listener

def 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 listener
        return False

def check_key(key):
    if key in [Key.up, Key.down, Key.left, Key.right]: 
        print('YES')

# Collect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

Upvotes: 9

Related Questions