Trouble with variable. [Python]
I have this variable on the beginning of the code:
enterActive = False
and then, in the end of it, I have this part:
def onKeyboardEvent(event):
if event.KeyID == 113: # F2
doLogin()
enterActive = True
if event.KeyID == 13: # ENTER
开发者_如何转开发if enterActive == True:
m_lclick()
return True
hookManager.KeyDown = onKeyboardEvent
hookManager.HookKeyboard()
pythoncom.PumpMessages()
and I get this error when I press enter first, and when I press F2 first:
UnboundLocalError: local variable 'enterActive' referenced before assignment
I know why this happens, but I don't know how can I solve it...
anyone?
See Global variables in Python. Inside onKeyboardEvent
, enterActive
currently refers to a local variable, not the (global) variable you have defined outside the function. You need to put
global enterActive
at the beginning of the function to make enterActive
refer to the global variable.
Approach 1: Use a local variable.
def onKeyboardEvent(event):
enterActive = false
...
Approach 2: Explicitly declare that you are using the global variable enterActive
.
def onKeyboardEvent(event):
global enterActive
...
Because you have the line enterActive = True
within the functiononKeyboardEvent
, any reference to enterActive
within the function uses the local variable by default, not the global one. In your case, the local variable is not defined at the time of its use, hence the error.
enterActive = False
def onKeyboardEvent(event):
global enterActive
...
Maybe you are trying to declare enterActive in another function and you aren't using the global statement to make it global. Anywhere in a function where you declare the variable, add:
global enterActive
That will declare it as global inside the functions.
Maybe this is the answer:
Using global variables in a function other than the one that created them
You are writing to a global variable and have to state that you know what you're doing by adding a "global enterActive" in the beginning of your function:
def onKeyboardEvent(event):
global enterActive
if event.KeyID == 113: # F2
doLogin()
enterActive = True
if event.KeyID == 13: # ENTER
if enterActive == True:
m_lclick()
return True
精彩评论