检测键盘输入

3

我是Python的新手,我正在尝试使用keyboard库检测f键何时被按下。这是我正在尝试运行的代码:

import keyboard

keyboard.on_press_key('f',here())

def here():
    print('a')

然而,当我将here()指定为回调函数时,在构建过程中会出现名称未定义的错误。

2
其他人已经提到了声明问题,但是你必须将keyboard.on_press_key('f',here())中的"here()"更改为"here",去掉括号。"here"是函数的地址,但是"here()"会立即给出函数调用的结果。而且你必须将第一个值传递给on_press_key()。 - kantal
3个回答

3
当您调用here()时,它还没有被定义,因此请将here()的声明移到您的代码之前。
另外,由于here应该是回调函数,所以您需要将其作为函数引用传递给on_press_key
import keyboard

def here():
    print('a')

keyboard.on_press_key('f', here)

谢谢,但是现在每当我运行这段代码时,它立即打印出“a”,即使没有按下“f”键,有什么原因吗? - Gary I
抱歉,我应该在答案中提到这一点,因为here是一个回调函数,所以你需要将它传递给on_press_key而不带上(),否则你只是将here的返回值传递给了on_press_key(没什么用!)。我会编辑答案以反映这一点。 - iz_

1
import keyboard
IsPressed = False

# once you press the button('f') the function happens once
# when you release the button('f') the loop resets

def here():
    print('a')

while True:
    if not keyboard.is_pressed('f'):
        IsPressed = False
    while not IsPressed:
        if keyboard.is_pressed('f'):
            here()
            IsPressed = True

# or if you want to detect every frame it loops then:

def here():
    print('a')

while True:
    if keyboard.is_pressed('f'):
        here()

1

只需将你的函数here()声明移动到上面,就像这样:

import keyboard

def here():
    print('a')

keyboard.on_press_key('f', here())

否则,here() 尚未声明,因此您会遇到错误。

NameError: 全局名称 '---' 未定义。Python 知道某些名称的用途(例如内置函数名称,如 print)。其他名称在程序中定义(例如变量)。如果 Python 遇到无法识别的名称,则可能会出现此错误。此错误的一些常见原因包括:

在另一条语句中使用变量之前忘记为其赋值 拼写内置函数的名称错误(例如,输入 "inpit" 而不是 "input")

对于您的情况,Python 解释器在该行上:
keyboard.on_press_key('f',here())

它不知道here()是什么,因为它还没有在内存中。

例子:

$ cat test.py 
dummy_call()

def dummy_call():
    print("Foo bar")
$ python test.py 
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    dummy_call()
NameError: name 'dummy_call' is not defined



$ cat test.py 
def dummy_call():
    print("Foo bar")

dummy_call()
$ python test.py 
Foo bar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接