代码如下:
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”并按下按钮。我错过了什么?非常感谢。你知道吗
您忘记在
main
函数中使passwordCorrect
全局化。您的main
函数有自己的局部passwordCorrect
变量,它与全局变量不同。你知道吗如果您使用的是python3,那么也可以将
global passwordCorrect
更改为nonlocal passwordCorrect
,这样checkPassword
函数就可以使用main
中定义的变量。你知道吗相关问题 更多 >
编程相关推荐