2010-09-03 71 views
0

我对代码的开头这个变量:变量故障。 [python]的

enterActive = False 

,然后在它的结束,我有这样的一部分:

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() 

,我得到这个错误时我按先进入,而当我按下F2第一:

UnboundLocalError: local variable 'enterActive' referenced before assignment 

我知道为什么会这样,但我不知道我该怎么解决呢?

有人吗?

回答

6

请参阅Global variables in Python。在onKeyboardEvent内部,enterActive当前引用的是局部变量,而不是您在函数外部定义的(全局)变量。你需要把

global enterActive 

在函数的开始,使enterActive指的是全局变量。

0

也许这就是答案:

Using global variables in a function other than the one that created them

您写这封信是一个全局变量,必须声明你知道什么 你在年初加入了“全球enterActive”做 你的函数:

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 
1
enterActive = False 

def onKeyboardEvent(event): 
    global enterActive 
    ... 
2

方法1:使用局部变量。

def onKeyboardEvent(event): 
    enterActive = false 
    ... 

方法2:显式声明,您使用的是全局变量enterActive

def onKeyboardEvent(event): 
    global enterActive 
    ... 

因为你具备的功能onKeyboardEvent内的线enterActive = True,在函数中的任何参考enterActive默认使用本地变量,而不是全球性的。在你的情况下,局部变量在使用时没有被定义,因此是错误。

+0

除非您想在局部范围内声明它们,否则您可以在不使用全局语句的情况下使用全局变量。 至少用于python 2。 – 2010-09-03 21:30:01

+0

你也可以在Python 3中。但OP *是*声明'enterActive = True'。 – 2010-09-03 21:30:47

0

也许你正在尝试在另一个函数中声明enterActive,并且你没有使用全局语句来使其成为全局语句。在声明变量的函数中的任意位置,请添加:

global enterActive 

这将在函数内声明为全局函数。