The print statement is running with the "if" statement, as well as "else", even though the conditions are met, the output is "Correct" and "Wrong". Furthermore, two "Wrong" statements are printed when the username and password are incorrect. I'd appreciate the help.
from tkinter import *
root = Tk()
root.title("Login")
root.resizable(False, False)
root.geometry("500x200")
image1 = PhotoImage(file="C:/Users/Cesar Alkaisy/Pictures/icon.png")
root.iconphoto(True, image1)
username_label = Label(root, text="Username", font=("Arial", 15, "bold"))
username_label.grid(column=1, row=0, padx=20, pady=20)
username_entry = Entry(root)
username_entry.grid(column=2, row=0)
password_label = Label(root, text="Password", font=("Arial", 15, "bold"))
password_label.grid(column=1, row=1)
password_entry = Entry(root)
password_entry.grid(column=2, row=1)
login_details = {"John": "123", "Jane": "321"}
def submit():
username = username_entry.get()
password = password_entry.get()
for login_detail in login_details:
if login_detail == username and login_details[login_detail] == password:
print("Correct")
else:
print("Wrong")
username_entry.delete(0, END)
password_entry.delete(0, END)
submit_button = Button(root, text="Submit", command=submit)
submit_button.grid(column=2, row=2, pady=10)
root.mainloop()
CodePudding user response:
Since you want to only print one thing ("Correct" if any of the details match, and "Wrong" only if none of them match), you should break the loop on a match, and only print "Wrong" if the loop isn't broken (by using for ... else
):
for login_detail in login_details:
if login_detail == username and login_details[login_detail] == password:
print("Correct")
break
else:
print("Wrong")
Another option would be to use the any
function, which does the same "test these conditions, break if any of them is true" logic for you automatically:
if any(
login_detail == username and login_details[login_detail] == password
for login_detail in login_details
):
print("Correct")
else:
print("Wrong")
You can make the for
a little simpler by iterating over login_details.items()
, which gives you tuples of the user and password:
if any(
detail_user == username and detail_password == password
for detail_user, detail_password in login_details.items()
):
print("Correct")
else:
print("Wrong")
and simpler yet by just comparing the tuple directly:
if any(
login_detail == (username, password)
for login_detail in login_details.items()
):
print("Correct")
else:
print("Wrong")
and simplest of all (now that the problem has been reduced to "does this (username, password)
tuple exist in login_details.items()
?") you can just use in
rather than any
:
if (username, password) in login_details.items():
print("Correct")
else:
print("Wrong")