Skip to content Skip to sidebar Skip to footer

Checking A Specific Key With Pynput In Python

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, nothi

Solution 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

Solution 2:

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

Try

ifkey.char == ('d'):

Full code being:

dpressed = 0

def on_press(key):

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

Solution 3:

for anyone having this problem. this is how i solve it

from pynput.keyboard import Key, Listener, KeyCode

    def print_key(*key): ## prints key that is pressed
    # keyis a tuple, so access the key(char) fromkey[1]
        ifkey[1] == KeyCode.from_char('d'):
            print('yes!')

    def key(): ## starts listener modulewith Listener(on_press=CT.print_key) as listener:
            listener.join()
    
    whileTrue:
        key()

souce: https://github.com/moses-palmer/pynput/issues/97

Solution 4:

Do you have a listener?

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

withListener(
    on_press=on_press,
    on_release=on_release) as listener:
listener.join()

Post a Comment for "Checking A Specific Key With Pynput In Python"