如何在pynput中检测keypress/release

How to detect keypress/release in pynput

我正在使用 pynput 来检测 keypress 释放,但我想在释放特定密钥时执行一些不同的代码。

这是我的代码:

1   from pynput import keyboard
2
3   def on_press(key):
4        try:
5           print('Key {0} pressed'.format(key.char))
6           #Add your code to drive motor
7       except AttributeError:
8           print('Key {0} pressed'.format(key))
9           #Add Code
10  def on_release(key):
11      print('{0} released'.format(key))
12      #Add your code to stop motor
13      if key == keyboard.Key.esc:
14          # Stop listener
15          # Stop the Robot Code
16          return False
17      if key == keyboard.Key.Qkey:
18          print ("fviokbhvxfb")
19
20  # Collect events until released
21  with keyboard.Listener(
22          on_press=on_press,
23          on_release=on_release) as listener:
24      listener.join()

他们指出不起作用的是:

if key == keyboard.Key.Qkey:
    print ("fviokbhvxfb")`

可能我的问题是 Qkey

我在第17行写了 我应该用什么代替它? 我正在尝试检测 q 是否被释放和按下,并且仅当它被按下而不是其他东西时才执行一些代码。

你可以这样做:

def on_release(key):
    print('{0} released'.format(key))
    #Add your code to stop motor
    if key == keyboard.Key.esc:
        # Stop listener
        # Stop the Robot Code
        return False
    if 'char' in dir(key):     #check if char method exists,
        if key.char == 'q':    #check if it is 'q' key
            print("fviokbhvxfb")