Reputation: 55
I'm pretty new to Python and I am trying to detect when the f key is pressed using the keyboard library. This is the code I am trying to run
import keyboard
keyboard.on_press_key('f',here())
def here():
print('a')
However when specifying here() as the callback, I get a name not defined error on building
Upvotes: 3
Views: 15221
Reputation: 54
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()
Upvotes: 1
Reputation: 16633
When you are calling here()
, it is not defined yet, so move the declaration of here()
above your code.
Also, because here
is supposed to be the callback, you need to pass it to on_press_key
as a function reference.
import keyboard
def here():
print('a')
keyboard.on_press_key('f', here)
Upvotes: 3
Reputation: 1740
Just move up you function here()
declaration like so:
import keyboard
def here():
print('a')
keyboard.on_press_key('f', here())
otherwise here()
is not yet declared hence your error.
NameError: global name '---' is not defined Python knows the purposes of certain names (such as names of built-in functions like print). Other names are defined within the program (such as variables). If Python encounters a name that it doesn't recognize, you'll probably get this error. Some common causes of this error include:
Forgetting to give a variable a value before using it in another statement Misspelling the name of a built-in function (e.g., typing "inpit" instead of "input")
For python interpreter in your case when it's on line:
keyboard.on_press_key('f',here())
it doesn't know what here()
is because it's not yet in memory.
Example:
$ 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
Upvotes: 1