My code is:
JavaScript
x
19
19
1
import keyboard
2
3
pressed = ""
4
5
def on_key_press():
6
print("Key pressed.")
7
global pressed
8
# Took me 1 hour to figure out this.
9
if charset.chars.__contains__(keyboard.read_key()):
10
print("processing slangs...")
11
print("*process*")
12
else:
13
print("registered key.")
14
pressed += keyboard.read_key()
15
print(pressed)
16
17
keyboard.on_press(on_key_press())
18
keyboard.wait()
19
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:
JavaScript
1
7
1
Traceback (most recent call last):
2
File "/usr/local/lib/python3.9/dist-packages/keyboard/_generic.py", line 22, in invoke_handlers
3
if handler(event):
4
File "/usr/local/lib/python3.9/dist-packages/keyboard/__init__.py", line 474, in <lambda>
5
return hook(lambda e: e.event_type == KEY_UP or callback(e), suppress=suppress)
6
TypeError: 'NoneType' object is not callable
7
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:
JavaScript
1
8
1
import keyboard
2
3
def test(a):
4
print(a)
5
6
keyboard.on_press(test)
7
keyboard.wait()
8
When you press random keys, it prints out KeyboardEvent(<key> down)
. The key string can be extracted using keyboard.read_key()
.