如何使用 raspberry pi 检测 python 中的按键

How to detect a key-press in python with raspberry pi

我正在使用键盘模块,但出现了这个错误。

我看过其他帖子,也照他们说的做了,用了 sudo pip3 install keyboard 还是不行。

import keyboard
loop = ""


while loop == "":

    if keyboard.read_key() == "w":
        print("You pressed w")



    if keyboard.read_key() == "a":


        print("You pressed a")

    if keyboard.read_key() == "s":
        print("You pressed s")



    if keyboard.read_key() == "d":
        print("You pressed d")

>>> 
==================== RESTART: /home/pi/Desktop/turret.py ====================
Traceback (most recent call last):
  File "/home/pi/Desktop/turret.py", line 7, in <module>
    if keyboard.read_key() == "w":
  File "/usr/local/lib/python3.7/dist-packages/keyboard/__init__.py", line 935, in read_key
    event = read_event(suppress)
  File "/usr/local/lib/python3.7/dist-packages/keyboard/__init__.py", line 924, in read_event
    hooked = hook(queue.put, suppress=suppress)
  File "/usr/local/lib/python3.7/dist-packages/keyboard/__init__.py", line 461, in hook
    append(callback)
  File "/usr/local/lib/python3.7/dist-packages/keyboard/_generic.py", line 67, in add_handler
    self.start_if_necessary()
  File "/usr/local/lib/python3.7/dist-packages/keyboard/_generic.py", line 35, in start_if_necessary
    self.init()
  File "/usr/local/lib/python3.7/dist-packages/keyboard/__init__.py", line 196, in init
    _os_keyboard.init()
  File "/usr/local/lib/python3.7/dist-packages/keyboard/_nixkeyboard.py", line 113, in init
    build_device()
  File "/usr/local/lib/python3.7/dist-packages/keyboard/_nixkeyboard.py", line 109, in build_device
    ensure_root()
  File "/usr/local/lib/python3.7/dist-packages/keyboard/_nixcommon.py", line 174, in ensure_root
    raise ImportError('You must be root to use this library on linux.')
ImportError: You must be root to use this library on linux.
>>> 

我 运行 代码并得到该错误。我以为我确实把它安装到 root 了。

当您需要 运行 您的脚本作为 root 时,它意味着像 sudo python3 ./yourfile.py

一样开始

不要忘记通过 chmod +x 使脚本可执行。