2010-09-03 55 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 

這將在函數內聲明爲全局函數。