首页 > 解决方案 > 如何查看使用 pynput python 3.7 按下的字符?

问题描述

您如何查看在 pynput 中按下了哪个按钮。

from pynput.keyboard import Key, Listener

def a(key):
    print('{0} pressed'.format(
        key))
    if key == 'a':
        print('ape')

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

看不到工作。

标签: pythonpython-3.xpynput

解决方案


from pynput.keyboard import Listener
def a(key):
    print(f"{key}, was pressed")
    if key.char == "a":
        print("foo")


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

输出:

q'q', was pressed
w'w', was pressed
a'a', was pressed
foo
s's', was pressed

但是,例如,如果您按下大写锁定,这将导致问题,因此我将放置在 try except 块中:

try:
    if key.char == 'a':
        print("foo")
except AttributeError:
    pass

推荐阅读