Skip to content
Advertisement

Python keyboard module error: TypeError: ‘NoneType’ object is not callable

My code is:

import keyboard

pressed = ""

def on_key_press():
    print("Key pressed.")
    global pressed
    # Took me 1 hour to figure out this.
    if charset.chars.__contains__(keyboard.read_key()):
        print("processing slangs...")
        print("*process*")
    else:
        print("registered key.")
        pressed += keyboard.read_key()
    print(pressed)

keyboard.on_press(on_key_press())
keyboard.wait()

I ran it as root. When I press a key, it prints the key as intended. But, when I press any key right after it, it just returns an error, like this:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/keyboard/_generic.py", line 22, in invoke_handlers
    if handler(event):
  File "/usr/local/lib/python3.9/dist-packages/keyboard/__init__.py", line 474, in <lambda>
    return hook(lambda e: e.event_type == KEY_UP or callback(e), suppress=suppress)
TypeError: 'NoneType' object is not callable

and it keeps print out errors like that, don’t matter what key I pressed. Please help.

Advertisement

Answer

not reading the docs be like
The function keyboard.on_press() invokes a callback, not a function. This code shows that:

import keyboard

def test(a):
    print(a)

keyboard.on_press(test)
keyboard.wait()

When you press random keys, it prints out KeyboardEvent(<key> down). The key string can be extracted using keyboard.read_key().

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement