变量有问题。[Python]

变量有问题。[Python],python,windows,Python,Windows,代码开头有一个变量: enterActive = False 最后,我有这一部分: def onKeyboardEvent(event): if event.KeyID == 113: # F2 doLogin() enterActive = True if event.KeyID == 13: # ENTER if enterActive == True: m_lclick()

代码开头有一个变量:

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()
当我先按enter键,再按F2键时,会出现这个错误:

UnboundLocalError: local variable 'enterActive' referenced before assignment
我知道为什么会发生这种情况,但我不知道如何解决它


有人吗?

也许这就是答案:

您正在写入全局变量,必须声明您知道 通过在开始时添加“global 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:使用局部变量

def onKeyboardEvent(event):
    enterActive = false
    ...
方法2:明确声明您正在使用全局变量
enterActive

def onKeyboardEvent(event):
    global enterActive
    ...
由于函数
onKeyboardEvent
中有一行
enterActive=True
,因此函数中对
enterActive
的任何引用默认使用局部变量,而不是全局变量。在您的情况下,局部变量在使用时未定义,因此会出现错误。

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

global enterActive

在函数的开头,要使
enterActive
引用全局变量。

可能您正试图在另一个函数中声明enterActive,而不是使用global语句使其成为全局变量。在函数中声明变量的任何位置,添加:

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

这将在函数中声明为全局变量。

您可以在不使用global语句的情况下使用全局变量,除非您希望在局部范围内声明它们。至少对于Python2,您也可以使用Python3。但是OP正在声明
enterActive=True