我有这个代码,获取用户名和密码。但问题是即使输入字段保持为空,它仍然可以运行。我希望如果输入字段为空,则用户必须再次输入用户名和密码。
from Tkinter import *
def onclick():
pass
import tkMessageBox
root = Tk()
root.title("Pantai Hospital")
root.geometry("200x200")
L1 = Label(root, text='Welcome to Pantai Hospital!')
L1.pack()
def messageWindow1():
win = Toplevel()
win.geometry("300x300")
frame1 = Frame(win)
frame1.pack()
frame2 = Frame (win)
frame2.pack()
frame3 = Frame (win)
frame3.pack()
L2 = "Login"
Label(frame1, text = L2).pack()
L3 = Label(frame2, text = "Username:")
L3.pack( side = LEFT, padx = 5, pady = 10)
username = StringVar()
E1 = Entry(frame2, textvariable = username, width = 40)
E1.pack( side = LEFT)
L4 = Label(frame3, text = "Password:")
L4.pack( side = LEFT, padx = 5, pady = 10)
password = StringVar()
E2 = Entry(frame3, textvariable = password, show = "*", width = 40)
E2.pack( side = LEFT )
validuser = ["yeojin" , "1234"]
v = 0
def loginCallBack() :
counter = 0
if username.get() and password.get() in validuser :
tkMessageBox.showinfo( "Welcome!" , "You are successfully logged on.")
else :
tkMessageBox.showinfo ("Login error", "please try again.")
while (counter < 3):
if username.get() and password.get() in validuser:
tkMessageBox.showinfo( "Welcome!" , "You are successfully logged on." )
else :
counter = counter + 1
B3 = Button ( win, text = "Login", command = loginCallBack)
B3.pack()
有没有人有任何想法?
答案 0 :(得分:1)
counter = 0
def loginCallBack() :
global counter
if username.get() == "" or password.get() == "":
tkMessageBox.showinfo("Login error", "Username and password fields can not be empty.")
elif username.get() == validuser[0] and password.get() == validuser[1]:
tkMessageBox.showinfo( "Welcome!" , "You are successfully logged on.")
else :
if counter < 3:
tkMessageBox.showinfo ("Login error", "Please try again.")
counter += 1
else:
#do whatever you want after 3 failed attempts
root.destroy()
你的问题在这一行:
if username.get() and password.get() in validuser:
Python解释器将该行视为
if (username.get()) and (password.get() in validuser)
因此,当您链接条件时,您需要单独检查它们。像
这样的东西 if username.get() in validuser and password.get() in validuser
。
如果您这样做,用户可以通过输入“1234”或“yeojin”字段登录,因此您应该专门检查这样的值。
if username.get() == validuser[0] and password.get() == validuser[1]
此外,要捕获空条目字段,您可以向loginCallBack()
添加另一个条件。如果其中一个输入字段为空,则可以弹出消息而不执行任何其他操作。
除此之外,使用while循环不是一个好主意,因为那里已经存在无限循环(主循环)。
您可以在回调中创建外的全局计数器,并且在每次失败的尝试增量时,该值和每次单击都会检查该值是否小于3。