Checking a specific key with pynput in Python

孤街浪徒 提交于 2020-05-27 13:21:06

问题


dpressed = 0

def on_press(key):

    if key == ('d'):
        global dpressed
        dpressed+=1
        logging.info("D: %s" % dpressed)

When I run this code and press d, nothing happens, which I suspect is because the key needs to be called something else when checked. Does someone know what it should be?


回答1:


For anyone else that may have this problem, I imported KeyCode from pynput.keybord at the top. Then I changed ('d') to KeyCode.from_char('d'). This should work for anyone with this problem. There is a great explanation here




回答2:


You need to format the key to char format else it won't be equeal to the specific character.

Try

if key.char == ('d'):

Full code being:

dpressed = 0

def on_press(key):

    if key.char == ('d'):
        global dpressed
        dpressed+=1
        logging.info("D: %s" % dpressed)



回答3:


Do you have a listener?

Without a listener the code wont work. Try adding this at the very end of your code.

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


来源:https://stackoverflow.com/questions/53693820/checking-a-specific-key-with-pynput-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!