Pynput的键盘监听器

时间:2018-11-06 19:38:17

标签: python keyboard

我正在尝试将键盘侦听器导入我的班级,但不断获得

NameError: name 'on_press' is not defined

这是我的代码:

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

也不确定100%的语句如何工作。

1 个答案:

答案 0 :(得分:1)

我可以使用他们的在线文档格式来工作:

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()