Search code examples
pythonpynput

How to check if special key been pressed using pynput


For normal alphanumeric keys it can be checked as fallow:

def on_press(key):
    try:
        if key.char == "a":
            # do sth

but what about special keys like f1 or Ctrl ?


Solution

  • According to the documentation, the function keys F1 to F20 are defined and many other keys like CTRL can also be checked. See the documentation for the internal names of the keys, but for F1 it should work as follows:

    from pynput.keyboard import Key
    
    def on_press(key):
        if key == Key.f1:
            # do something