Search code examples
pythonpynput

Checking if a certain key is being pressed


i'm fairly new to python. This is my code till now.

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()

I want to check if the Key that is pressed is the lower a. But till now it prints out "keyboard pressed" no matter if i press the 'a' key or any other key. Thanks for any help


Solution

  • You need to check the key.char attribute and also use quotes to '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()
    

    Try to use the debugger it will help you a lot.