4
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?

Mats
  • 89
  • 1
  • 1
  • 7

4 Answers4

5

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)
xiawi
  • 1,772
  • 4
  • 19
  • 21
4

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

Mats
  • 89
  • 1
  • 1
  • 7
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
    # key is a tuple, so access the key(char) from key[1]
        if key[1] == KeyCode.from_char('d'):
            print('yes!')

    def key(): ## starts listener module
        with Listener(on_press=CT.print_key) as listener:
            listener.join()
    
    while True:
        key()

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

0

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()
64humans
  • 57
  • 1
  • 13
  • I have that at the end already, and my code works if i change ('d') to Key.shift. I just don't know the code for the d-key. – Mats Dec 09 '18 at 15:42
  • @mats Try checking if the key is equal to d like this `key.char == 'd'` – 64humans Dec 09 '18 at 15:49