I am creating a login system which retrieves the details within an entry box and compares it to details on a database. If the details entered are found on the database, the Bottom() function is ran. If details are not found, the user is requested to try again.
Currently, the program loops until it is found. However, because I have set up an else statement, if the first item in the database is not the details entered, the else section will still run. Is there a way I can change this so that else is else and last value in the database?
Here is the function:
#Retrieves the information entered into entry box
def Get_Details():
user_namev2=user_name.get().lower() #Make it so entry box goes red if passwords password is incorrect, and red if username is incorrect/not fault
user_passwordv2=user_password.get().lower()
with open ('Accounts.csv', 'r') as Account_file:
reader = csv.reader(Account_file)
for row in reader:
for field in row:
if row[0] == user_namev2 and row[1] == user_passwordv2:
Bottom()
break
else:
nomatch_label = Label(canvas, width = 40, height = 2, text = "USERNAME AND PASSWORD NOT FOUND", fg = "red", bg = "gray21", font = font2)
canvas_nomatch_label = canvas.create_window(500, 550, window = nomatch_label)
name_entry.config(fg = "red")
password_entry.config(fg="red")
break
This should hopefully work the way you intended, now it loops over the rows and checks username/password against row[0] and row[1]. If it finds a match it breaks and will not execute the else connected to the for-loop.
Also I removed the for-loop over row as the field variable wasn't used anyhow.
#Retrieves the information entered into entry box
def Get_Details():
user_namev2=user_name.get().lower() #Make it so entry box goes red if passwords password is incorrect, and red if username is incorrect/not fault
user_passwordv2=user_password.get().lower()
with open ('Accounts.csv', 'r') as Account_file:
reader = csv.reader(Account_file)
for row in reader:
if row[0] == user_namev2 and row[1] == user_passwordv2:
Bottom()
break
else:
nomatch_label = Label(canvas, width = 40, height = 2, text = "USERNAME AND PASSWORD NOT FOUND", fg = "red", bg = "gray21", font = font2)
canvas_nomatch_label = canvas.create_window(500, 550, window = nomatch_label)
name_entry.config(fg = "red")
password_entry.config(fg="red")
#Retrieves the information entered into entry box
def Get_Details():
user_namev2=user_name.get().lower() #Make it so entry box goes red if passwords password is incorrect, and red if username is incorrect/not fault
user_passwordv2=user_password.get().lower()
with open ('Accounts.csv', 'r') as Account_file:
reader = csv.reader(Account_file)
found = False
for row in reader:
for field in row:
if row[0] == user_namev2 and row[1] == user_passwordv2:
Bottom()
found = True
break
else:
if not found:
nomatch_label = Label(canvas, width = 40, height = 2, text = "USERNAME AND PASSWORD NOT FOUND", fg = "red", bg = "gray21", font = font2)
canvas_nomatch_label = canvas.create_window(500, 550, window = nomatch_label)
name_entry.config(fg = "red")
password_entry.config(fg="red")
break
note that the else has been shifted back to pair with the for loop
Related
I'm making a user interface but my for loop is not working. i wanted to say somthing when th username was alredy used butmy code yust skips the for loop and then append the username and password to the list. in the txt file stand in each line username;password
import tkinter as tk
from tkinter import *
root = Tk()
root.title("WRTS oefentoets")
root.geometry("735x355")
def sign():
userfile = open("users.txt", "a+")
users = list(userfile.readlines())
found = 0
for line in users:
parts = line.split(";")
if parts[0] == username.get():
found = 1
break;
if found == 1:
bestaatal.place(x= 300, y= 200)
else:
with open('users.txt', "a+") as file_object:
# Move read cursor to the start of file.
file_object.seek(0)
# If file is not empty then append '\n'
data = file_object.read()
if len(data) > 0:
file_object.write("\n")
# Append text at the end of file
file_object.write(username.get() + ";" + password.get())
username = Entry(root, bg = 'black', fg = 'magenta')
password = Entry(root, bg = 'black', fg = 'magenta')
signin = Button(root, bg = 'black', fg = 'magenta', text = 'sign up', command = sign, width = 7)
signin.place(x= 343, y= 181)
username.place(x=262.5, y= 135)
password.place(x=262.5, y= 157.5)
.readlines on a file in append mode starts reading from the end of that file
So, since from userfile you're only reading, just open it in read mode:
with open("users.txt", 'r') as userfile:
... # your code
I have created an if statement to check if the username and password and username entered is the same to the username and password in the textile. I have been able to display if the data inputted is correct or not. I now want to add a command into the if statement e.g. command = main_menu if the data inputted is correct (I am using tkinter)
This is the if code I have so far:
def validation(username1, password1):
file = open("Accounts.txt", "r")
for line in file:
line = line.split("\n")
line = line[0].split(" ")
if username1 == line[0] and password1 == line[1]:
valid = Label(root, text="Data: Found")
valid.place(x=290, y=130)
else:
valid = Label(root, text="Data: Not found")
valid.place(x=280, y=130)
file.close()
Any ideas on how to do this?
Thanks xx
I am currently making a python GUI with a login verification. I am using a text file to verify the login details. When I try to compare the userid and password against data from the file, it goes into the else condition and prints "Fail".
I am using tkinter for the GUI, but the login details do not work.
from tkinter import *
def verify_login():
file = open("login.txt","r")
for row in file:
field = row.split(",")
if username.get() == field[0] and password.get() == field[1]:
print("Correct!")
else:
print("Fail")
### LOGIN SCREEN ###
def LoginPage():
global username
global password
login_screen=Tk()
login_screen.title("Login")
login_screen.geometry("300x250")
Label(login_screen, text="Please enter login details").pack()
Label(login_screen, text="").pack()
Label(login_screen, text="Username").pack()
username=StringVar()
password=StringVar()
username_login = Entry(login_screen, textvariable=username)
username_login.pack()
Label(login_screen, text="").pack()
Label(login_screen, text="Password").pack()
password_login= Entry(login_screen, textvariable=password, show= '*')
password_login.pack()
Label(login_screen, text="").pack()
Button(login_screen, text="Login", width=10, height=1,command=verify_login).pack()
login_screen.mainloop(
### MAIN SCREEN ###
def Startpage():
global gui
gui=Tk(className="Login Form")
gui.geometry("500x200")
button = Button(gui, text='Login', width=20, height=3, bg='#0052cc', fg='#ffffff', activebackground='#0052cc', activeforeground='#aaffaa', command=LoginPage).pack()
gui.mainloop()
Startpage()
my text file has logins and passwords in this format:
login,a,yex,joe,morgan,1,sanjay,2
maybe username and password have tailing whitespaces, like sanjay and sanjay are not same.
to clean it up you can do this before comparing:
username.get().rstrip()
password.get().rstrip()
this rstrip() function will remove the tailing whitespaces.
also, make sure, your file has every username password pair in a new line.
then you can do this:
for row in file.readlines():
so, your verify_login() function should be like this:
def verify_login():
file = open("login.txt","r")
for row in file.readlines():
field = row.split(",")
if username.get().rstrip() == field[0] and password.get().rstrip() == field[1]:
print("Correct!")
else:
print("Fail")
your text file format
login,a,yex,joe,morgan,1,sanjay,2
apears to have the type of values stored in the first word login
this means when you access item 0 from the list you are getting "login" instead of "a"
you should change the index you try to acces to 1 & 2 instead of 0 & 1
def verify_login():
file = open("login.txt","r")
for row in file:
field = row.split(",")
if username.get() == field[1] and password.get() == field[2]:
print("Correct!")
else:
print("Fail")
The below should work for you.
verify_login is a boolean function now.
def verify_login(user_name,password):
with open("login.txt","r") as f:
for row in f:
row = row.strip()
field = row.split(",")
if user_name == field[0] and password == field[1]:
return True
return False
print(verify_login('Jack','pp'))
print(verify_login('usr1','pwd1'))
login.txt
usr1,pwd1
usr5,pwd5
output
False
True
I have a label that I want to be empty until a button is pressed that searches a csv file to find scores from entries of the same name as an entered name. Any values that are found to be displayed into a label, currently only the first values are shown by the list, thanks.
entSearch = Entry(window)
lblSearch = tkinter.Label(window, text="Search for your previous scores!")
btnSearch = Button(window, text="Search!",command=search)
lblSearched = tkinter.Label(window, text="")
def search():
file1=open("scores.csv","r")
csvreader=csv.reader(file1)
for x in csvreader:
if entSearch.get() == x[0]:
results = x[0]+" "+x[1]+"\n"
lblSearched.config(text=results)
You can connect all in one text and later put it in Label
searched_text = entSearch.get()
full_text = ''
for row in csvreader:
if row[0] == searched_text:
# with '\n'
full_text += "{} {}\n".format(row[0], row[1])
lblSearched.config(text=full_text)
or with join() (it will not add \n after last line)
searched_text = entSearch.get()
all_lines = []
for row in csvreader:
if row[0] == searched_text:
# WITHOUT '\n'
all_lines.append("{} {}".format(row[0], row[1]))
full_text = '\n'.join(all_lines)
lblSearched.config(text=full_text)
In your current code you can use
lblSearched['text'] += results
or
lblSearched.config(text=lblSearched.cget('text') + results)
but it is less readable.
I have this code which asks user to select one of the choices. I used radiobuttons. After the user select his choice, the choice will be use another if statement. I already assigned the choice's variable as variable = specialistchoose. But when I use the specialistchoose or specialistchoose.get(), it does not work. Can anyone help?
specialistchoose = IntVar()
r1 = Radiobutton (f2, text = "Cardiology", variable = specialistchoose, value = 1, command = command_r1 )
r1.grid(row = 4, column = 0, stick = W)
r2 = Radiobutton (f2, text = "Gastroenterology", variable = specialistchoose, value = 2, command = command_r2)
r2.grid(row = 4, column = 1,stick = W )
r3 = Radiobutton (f2, text = "Dermatology", variable = specialistchoose, value = 3, command = command_r3)
r3.grid (row = 4, column = 2,stick = W )
r4 = Radiobutton (f2, text = "Psychiatry", variable = specialistchoose, value = 4, command = command_r4)
r4.grid (row = 5, column = 0,stick = W )
r5 = Radiobutton (f2, text = "Dentist", variable = specialistchoose, value = 5, command = command_r5)
r5.grid(row = 5, column = 1,stick = W )
f2.place(relx = 0.01, rely = 0.125, anchor = NW)
Label(f1, text = "Specialist").place(relx = .06, rely = 0.125, anchor = W)
f1.grid(stick = W)
if specialistchoose.get() == "Cardiology":
file = open ("test2.txt", "w")
file.write ("Specialist : Cardiology")
file.close()
elif specialistchoose.get() == "Gastroenterology":
file = open ("test2.txt", "w")
file.write ("Specialist : Gastroenterology")
file.close()
elif specialistchoose.get() == "Dermatology":
file = open ("test2.txt", "w")
file.write ("Specialist : Dermatology")
file.close()
elif specialistchoose.get() == "Psychiatry":
file = open ("test2.txt", "w")
file.write("Specialist : Psychiatry")
file.close()
elif specialistchoose.get() == "Dentist":
file = open ("test2.txt", "w")
file.write("Specialist : Dentist")
file.close()
note : this is just the sample of a longer code.
Since you are get()ting their values only right after they created, you'll get only their initial value and nothing more.
Try to get their value using command, or another button.
No idea what do you have under command_rXs but you should split those if's and put under respective commands.
Also, since your variables are IntVar() and you'll be getting value which will be between 1 and 5 inclusive since you assigned as such.
def command_r1():
with open('test2.txt', 'w') as file:
file.write ("Specialist : Cardiology")
def command_r2():
with open('test2.txt', 'w') as file:
file.write ("Specialist : Gastroenterology")
#etc...
or create a button, when that's clicked it'll get the value and does all those if-else things.
def external_button_callback():
radioValue = specialistchoose.get()
if radioValue == 1:
with open('test2.txt', 'w') as file:
file.write ("Specialist : Cardiology")
#etc...
btn = Button(f2, text= "Get Value" command = external_button_callback)
btn.grid(row=6, column=0)
Another little thing is, when using files, it is better to use with statement since it handles closing automatically when you move out of scope and you don't need to worry about closing everytime.
And everytime you change value, that txt file will be created from scratch since you open it on w mode. I don't know if that's what you wanted or not but wanted to give a heads up.
The value of radiobutton variable has nothing to do with its text. You declared the variable specialistchoose to be IntVar so it will be some int.
if specialistchoose.get() == "Cardiology": will never be True
Yesterday i answered your question on a very same topic here:Gray out a frame after clicking a radiobutton Tkinter
If you alter the func to something like this:
def func():
print specialistchoose.get()
You will be able to see what values each radiobutton gets when it is pressed.
From there you can make a condition if they are pressed or not.