tags:

views:

54

answers:

5

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?

A: 

Maybe this is the answer:

http://stackoverflow.com/questions/423379/global-variables-in-python

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
dantje
+1  A: 
enterActive = False

def onKeyboardEvent(event):
    global enterActive
    ...
rkhayrov
+1  A: 

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.

Justin Ardini
You can use global variables without the global statement unless you want to declare them inside a local scope.For python 2 at least.
Matthew Mitchell
You can in Python 3 too. But the OP *is* declaring `enterActive = True`.
Justin Ardini
+5  A: 

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.

Richard Fearn
A: 

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.

Matthew Mitchell