0

我的代码是:

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

我以root身份运行它。当我按下一个键时,它会按预期打印该键。但是,当我在它之后按下任何键时,它只会返回一个错误,如下所示:

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

它会不断打印出这样的错误,不管我按什么键。请帮忙。

4

2 回答 2

0

on_key_press我认为调用函数时唯一需要删除括号


keyboard.on_press(on_key_press())

对此:


keyboard.on_press(on_key_press)

我的猜测是该方法keyboard.on_press将函数作为参数,而不是可调用对象

于 2021-07-12T03:11:16.137 回答
0

不阅读文档就像
函数keyboard.on_press()调用回调而不是函数。这段代码表明:

import keyboard

def test(a):
    print(a)

keyboard.on_press(test)
keyboard.wait()

当您按随机键时,它会打印出KeyboardEvent(<key> down). 可以使用 提取密钥字符串keyboard.read_key()

于 2021-07-23T08:34:25.173 回答