Search code examples
pythonkeyboarddetection

Why pynput doesn't detect numeric keyboard presses?


I'm using python 3.7 on windows 7.

Is there any way to detect number (for example: "1") key presses in pynput module?

I have tried many other modules and i got nothing except for tkinter which needs a window but i don't want that.

from pynput import keyboard  
def on_press(key):
     print(key)
     if str(format(key)) == 'Key.1':
         print('Exiting...')
         return False 
with keyboard.Listener(on_press = on_press) as listener:
     listener.join()

It actually only prints the pressed key and never brakes(doesn't accept the numeric input).


Solution

  • The code you've provided seems to be trying to detect Numeral key '1' rather than 'Num lock'.

    @BoarGules has provided a complete answer. Just to add a bit of clarification:

    When you monitor keyboard using pynput, if trying to detect a control key, you should compare it with appropriate pynput.keyboard.Key object. In case of checking for num lock, your code should look like this:

    if key == keyboard.Key.num_lock:
        print('exiting')
    

    On the other hand, if you're looking for an alpha-numeric key, compare it with pynput.keyboard.KeyCode:

    if key == keyboard.KeyCode(char = '1'):
        print('exiting')