使用Python GUI的密码和用户名

时间:2017-01-10 12:07:30

标签: python user-interface tkinter

这是一个简单的GUI程序,用于检查用户是否输入了正确的用户名和密码。问题是即使输入正确的用户名和密码,即admin和secret,它仍会输出'Invalid Login'

这是代码:

from tkinter import *
import tkinter.messagebox as box

def dialog1():
    box.showinfo('info','Correct Login')
def dialog2():
    box.showinfo('info','Invalid Login')

window = Tk()
window.title('Countries Generation')

frame = Frame(window)

Label1 = Label(window,text = 'Username:')
Label1.pack(padx=15,pady= 5)

entry1 = Entry(window,bd =5)
entry1.pack(padx=15, pady=5)

username = entry1.get()

Label2 = Label(window,text = 'Password: ')
Label2.pack(padx = 15,pady=6)

entry2 = Entry(window, bd=5)
entry2.pack(padx = 15,pady=7)

password = entry2.get()

if (username == 'admin' and  password == 'secret'):
    btn = Button(frame, text = 'Check Login',command = dialog1)
else:
    btn = Button(frame, text ='Check Login', command = dialog2)

btn.pack(side = RIGHT , padx =5)
frame.pack(padx=100,pady = 19)
window.mainloop()

1 个答案:

答案 0 :(得分:0)

我认为你应该考虑使用一个类而不是原始代码,你将有一个很好的控制。 我只是更正了你的逻辑,而不是在点击按钮之前检查它,然后运行

之后,您的代码看起来像这样

from tkinter import *
import tkinter.messagebox as box

def dialog1():
    username=entry1.get()
    password = entry2.get()
    if (username == 'admin' and  password == 'secret'):
        box.showinfo('info','Correct Login')
    else:
        box.showinfo('info','Invalid Login')


window = Tk()
window.title('Countries Generation')

frame = Frame(window)

Label1 = Label(window,text = 'Username:')
Label1.pack(padx=15,pady= 5)

entry1 = Entry(window,bd =5)
entry1.pack(padx=15, pady=5)



Label2 = Label(window,text = 'Password: ')
Label2.pack(padx = 15,pady=6)

entry2 = Entry(window, bd=5)
entry2.pack(padx = 15,pady=7)




btn = Button(frame, text = 'Check Login',command = dialog1)


btn.pack(side = RIGHT , padx =5)
frame.pack(padx=100,pady = 19)
window.mainloop()

希望能帮助您了解之前代码的错误