检查是否按下了某个键

Checking if a certain key is being pressed

我是 python 的新手。到目前为止,这是我的代码。

from pynput.keyboard import Listener


counta = 0

def on_press(key):


    if key == a:
        print("a is pressed")
        global counta
        counta += 1
        print(counta)

    else:
        print("keyboard pressed")


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

我想检查按下的键是不是小a。但是到目前为止,无论我按 'a' 键还是任何其他键,它都会打印出 "keyboard pressed" 。 感谢您的帮助

您需要检查 key.char 属性并使用引号 'a'

from pynput.keyboard import Listener

counta = 0

def on_press(key):

    if key.char == 'a':
        print("a is pressed")
        global counta
        counta += 1
        print(counta)

    else:
        print("keyboard pressed")


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

尝试使用调试器,它会对你有很大帮助。