麻烦变量.[蟒蛇]

Bru*_*dy' 0 python windows

我在代码的开头有这个变量:

enterActive = False
Run Code Online (Sandbox Code Playgroud)

然后,在最后,我有这个部分:

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()
Run Code Online (Sandbox Code Playgroud)

当我先按Enter键然后先按F2键时出现此错误:

UnboundLocalError: local variable 'enterActive' referenced before assignment
Run Code Online (Sandbox Code Playgroud)

我知道为什么会这样,但我不知道怎么解决它...

任何人?

Ric*_*arn 6

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

global enterActive
Run Code Online (Sandbox Code Playgroud)

在函数的开头,enterActive引用全局变量.