为什么我的Tkinter Python代码不能像我预期的那样工作?

2024-09-20 05:51:21 发布

您现在位置:Python中文网/ 问答频道 /正文

代码如下:

from tkinter import *

def main():
    pw = ''
    passwordCorrect = False

    window = Tk()

    instructionLabel = Label(window,text='Enter your password:')
    entryBox = Entry(window)
    def checkPassword():
        if entryBox.get() == 'password':
            global passwordCorrect
            passwordCorrect = True

    confirmButton = Button(window,text='Confirm',command=checkPassword)

    instructionLabel.pack()
    entryBox.pack()
    confirmButton.pack()
    window.mainloop()

    if passwordCorrect:
        print('Access granted')
    else:
        print('Access denied')
main()

当我关闭窗口时,总是会收到消息“Access denied”(预期为“Access granted”),即使我在输入框中输入“password”并按下按钮。我错过了什么?非常感谢。你知道吗


Tags: textifaccessmaindefpasswordwindowpack
1条回答
网友
1楼 · 发布于 2024-09-20 05:51:21

您忘记在main函数中使passwordCorrect全局化。您的main函数有自己的局部passwordCorrect变量,它与全局变量不同。你知道吗

如果您使用的是python3,那么也可以将global passwordCorrect更改为nonlocal passwordCorrect,这样checkPassword函数就可以使用main中定义的变量。你知道吗

相关问题 更多 >