Python 检测键盘输入
我对Python非常陌生,我正在尝试使用键盘库检测何时按下f键。这就是我试图运行的代码Python 检测键盘输入,python,keyboard,Python,Keyboard,我对Python非常陌生,我正在尝试使用键盘库检测何时按下f键。这就是我试图运行的代码 import keyboard keyboard.on_press_key('f',here()) def here(): print('a') 但是,当将here()指定为回调时,我在生成时收到一个名未定义的错误,当您调用here()时,它尚未定义,因此将here()的声明移到代码上方 另外,因为这里的应该是回调,所以您需要将它作为函数引用传递给按下键时的 import keyboard d
import keyboard
keyboard.on_press_key('f',here())
def here():
print('a')
但是,当将here()指定为回调时,我在生成时收到一个名未定义的错误,当您调用
here()
时,它尚未定义,因此将here()
的声明移到代码上方
另外,因为这里的应该是回调,所以您需要将它作为函数引用传递给按下键时的
import keyboard
def here():
print('a')
keyboard.on_press_key('f', here)
只需向上移动函数here()
声明,如下所示:
import keyboard
def here():
print('a')
keyboard.on_press_key('f', here())
否则,here()
尚未声明,因此会出现错误
NameError:未定义全局名称“---”,Python知道其用途
某些名称的名称(例如内置函数的名称,如print)。
其他名称在程序中定义(如变量)。如果
Python遇到一个它无法识别的名称,您可能会
获取此错误。此错误的一些常见原因包括:
在将变量用于另一个变量之前忘记给它赋值
语句拼错了内置函数的名称(例如键入
“输入”而不是“输入”)
对于联机的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
$cat test.py
虚拟调用()
def dummy_call():
打印(“Foo-bar”)
$python test.py
回溯(最近一次呼叫最后一次):
文件“test.py”,第1行,在
虚拟调用()
NameError:未定义名称“dummy_call”
$cat test.py
def dummy_call():
打印(“Foo-bar”)
虚拟调用()
$python test.py
富吧
其他人已经提到了声明问题,但您必须将键盘中的“here()”更改为“here()”。按键盘上的键('f',here())将其更改为“here”,而不必使用密码。“here”是函数的地址,但“here()”立即给出函数调用的结果。您必须将第一个值传递给on_press_key()。谢谢,但是现在每当我运行此代码时,即使不按“f”键,它也会立即打印出“a”,有什么原因会发生这种情况吗?对不起,我应该在回答中提到这一点,但因为这里是一个回调,您需要在不使用()
的情况下,将其传递到on\u press\u key
,否则您只是在on\u press\u key
上给出的返回值(不太有用!)。我将编辑答案以反映这一点。
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()