python - 如何检测 pynput 中的按键/释放

标签 python 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")

关于python - 如何检测 pynput 中的按键/释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60016734/

相关文章:

Python - 读取和删除文件的顶行而不将其加载到内存中

python - 尝试创建一个鼠标记录器,但它一直在无限循环?

python - 如何在 Pynput 中使用侧面鼠标按钮?

python - 出于神秘原因,函数为 numpy 数组定义了不需要的属性

python - 为什么不能为非 float 定义 `round`?

python - 在 python 中显示像素数组中的图像时出错

python - "No such file or directory"与 firebase_admin python 库

python - key.char 在 Python Pynput 中使用 Key.f5 时给出 AttributeError

python - 设置可变数量的热键监听器 pynput