How do I add a command (tkinter) in an if statement? - python

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

Related

Changing stored scores with certain username in a txt file. Python

I just started my gcse computer science course where we learn python. I need help with updating a user's score to a certain account. I am storing usernames passwords and scores in a text file and need to know how to change a score from a certain account. My text file is set out like this:
Bobby,pass,98
Pip,Noob,19
pog,man,1234
E.g Bobby is the username and pass is the password and 98 is the score so what I need is a way to scan for that certain username and change the score (98).
The code that I use for creating an account and logging in is this:
def SignUp():
print("""Please enter a username and password.""")
newUsername = input("Your username: ")
#Now askes for a password
print("""Cool now enter a password
""")
newPassword = input("Your Password: ")
print("Nice.")
newscore = input("Now give me a score")
#Puts the username and password into a txt
file = open("Login.txt","a")
file.write("""
""")
file.write (newUsername)
file.write (",")
file.write (newPassword)
file.write (",")
file.write (newscore)
file.close()
def Login():
userLogin = input("Please enter your username. ")
userPass = input("Password: ")
logged_in = False
with open('Login.txt', 'r') as file:
for line in file:
username, password, score = line.split(',')
if username == userLogin:
# Check the username against the one supplied
logged_in = password == userPass
print(str(score))
print("you logged in")
break
SignUp()
Login()
I'm quite new to python as you can probably tell so any help will be appreciated.
The easiest way is to read the entire file, then rewrite the entire thing with the changed number. This is only practical with small files:
def changeScore(username, newScore):
file = open("Login.txt", "r")
lines = file.readlines()
file.close()
file = open("Login.txt", "w")
for line in lines:
data = line.split(",")
if data[0] == username:
data[2] = str(newScore) + "\n"
file.write(",".join(data))
else:
file.write(line)
file.close()
One way to do this is to find the line you want by the provided userName, and then change the line. You can just re-write all the lines back into the txt file.
def changeScore(userLogin, newScore):
with open('Login.txt', 'r') as file:
lines = file.readlines()
for line in lines:
if line.startswith(userLogin):
username, password, score = line.split(",")
line = f"{username},{password},{newScore}\n"
with open('Login.txt', 'w') as file:
file.write("".join(lines))

Login verification fails while checking for userid, password from text file

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

How to read external file in python?

i need to be able to save and get usernames and passwords from an external file. this is what i have done so far however it constantly says that username or password is incorrect even when i enter it correctly. does anyone know how to fix this problem.
this is my current code
import time
print("Welcome...")
welcome = input("Do you have an acount? y/n: ")
if welcome == "n":
while True:
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
file = open("gcsetask.txt", "a")
file.write(username + ":" + password)
file.write('\n')
file.close()
welcome = "y"
time.sleep(0.4)
print("now lets login")
break
print("Passwords do NOT match!")
if welcome == "y":
while True:
login1 = input("Enter username:")
login2 = input("Enter Password:")
file = open("gcsetask.txt", "r")
data = file.readlines()
file.close()
if data == (login1 + ":" + login2):
print("Welcome")
break
print("Incorrect username or password.")
Three methods to read a file
read() It returns the read bytes in form of a string.
fileObject.read()
You can also define, how many bytes to read by
`fileObject.read([n]) //If n is not define, it will read the whole file`
readline([n]) It reads the line and return in the form of string, It only read single line
fileObject.readline([n])
readlines() It reads all the lines of the file and return each line a string element in a list
fileObject.readlines()
Hope it helps
I have changed the code to look at each line of that file. Allowing multiple users.
import time
print("Welcome...")
welcome = input("Do you have an acount? y/n: ")
if welcome == "n":
while True:
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
file = open("gcsetask.txt", "a")
file.write(username+":"+password)
file.write('\n')
file.close()
welcome = "y"
time.sleep(0.4)
print("now lets login")
break
print("Passwords do NOT match!")
if welcome == "y":
while True:
login1 = input("Enter username:")
login2 = input("Enter Password:")
file = open("gcsetask.txt", "r")
data = file.readlines()
file.close()
for line in data:
if line == (login1+":"+login2+"\n"):
print("Welcome")
break
else:
print("Incorrect username or password.")
The function readlines() saves each line in a string inside a list.
If a file contains-
first line
second line
readlines() gives: ['first line','second line']
Try accessing them using index such as data[0] and data[1]
When you use file.readlines(), the function returns a list of all lines in the file. Thus, when you define data as:
data = file.readlines()
if you print(data), you get something similar to:
['user:pass\n'] # note the the \n at the end
Then, in the following line:
if data == (login1+":"+login2):
you're trying to compare a string (login1+":"+login2) with a list, which is always False because they have different type.
Changing the condition to:
if login1+":"+login2 in data:
should fix this problem (but you'll have a different one, see below).
About the trailing \n:
file.readlines() splits the lines in a list, but does not remove the newline character. This will cause your test to still fail always, because you don't account for it in the test.
Possible solutions are:
1) include the \n in the string you search:
if '{}:{}\n'.format(login1,login2) in data:
2) read the whole file and use splitlines instead, which will remove the newline characters
data = file.read().splitlines()
The readlines method returns the list of lines which you need to iterate on it to find the appropriate login information.
data = file.readlines()
login_info = f"{login1}:{login2}\n"
if login_info in data:
print("Welcome")
break
And also you can remove \n from the end of each line using splitlines.
data = file.read().splitlines()
login_info = f"{login1}:{login2}"
if login_info in data:
print("Welcome")
break
And another alternative is remove \n from parsed lines manually.
data = [line.rstrip('\n') for line in file.readlines()]
login_info = f"{login1}:{login2}"
if login_info in data:
print("Welcome")
break

How to grab a certain word from a .txt file given what it begins and ends with

DISCLAIMER:
I'm using python 3!
FUNDEMENTAL CODE:
So I have this code:
def login(userlogin):
with open('usernames.txt') as input_data: # Grabs username from usernames.txt CHANGE DOESN'T WORK FOR MULTIPLE PEOPLE
for user in input_data:
if user.strip() == userlogin:
break
for user in input_data:
if user.strip() == '0':
break
print(user)
while(True):
userinput = input('')
login(userinput)
and also .txt file in the same directory, called usernames.txt which you can see here:
admin010
guest020
admin01030
user040
DESIRE:
I want the code to output the username corresponding in the .txt file based on the name inputted, so for example, if you inputted 'admin' it would find text in the text document that starts with admin and find its ending which is always a '0' and output admin010. However, I want it to make sure, when you type admin01 it would output admin01030. So the usernames are in the form, name + value (2 digits i.e. a value of 7 would be 07) + a zero ('0' string).
PROBLEM:
The code isn't working, no matter my input it always outputs the last word in the .txt document. I'm not sure why, any help would be great.
If the format is "name + two-digits + 0", then you want to match the name with a line less the last three characters:
for user in input_data:
if userlogin == user.rstrip()[:-3] # strip trailing whitespace and remove last 3 chars
print(user)
Can be written fairly compactly in this way, if I understand you.
def login(userlogin):
with open('usernames.txt') as usernames:
for line in usernames:
username = line.strip()
if username.startswith(userlogin+'0') and len(username)==len(userlogin)+3:
print (username)
return
print ('no match')
for poss in ['admin', 'admin01', 'guest', 'user']:
print (poss, ': ', end=''); login(poss)
Output:
admin : admin010
admin01 : admin01030
guest : guest020
user : user040
Hi please see below code. But I need to know why admin01 would match admin01030 only? since admin010 also starts with admin01
def login(userlogin):
with open(
'usernames.txt') as input_data: # Grabs username from usernames.txt CHANGE DOESN'T WORK FOR MULTIPLE PEOPLE
for user in input_data:
if user.strip() == '0':
break
if user.strip().startswith(userlogin, 0, len(userlogin)):
break
print(user)
while True:
userinput = input('')
login(userinput)
What you want to do is basically check if a string has a substring.
In the below example when the button is pressed, it checks if the file 'usernames.txt' that is in the same directory, has a string that matches exactly the user input before reaching the last 3 letters which are reserved for value and zero. Then parses it to name, value and '0':
import tkinter as tk
def login():
with open('usernames.txt') as fin:
users_list = fin.readlines()
for user in users_list:
user = user.strip() # to lose \n
if user[:-3] == query.get():
nam_lbl['text'] = user[:-3]
val_lbl['text'] = user[-3:-1]
zero_lbl['text'] = user[-1]
root = tk.Tk()
query = tk.Entry(root)
nam_lbl = tk.Label(root, text="Name: ")
val_lbl = tk.Label(root, text="Value: ")
zero_lbl = tk.Label(root, text="Zero: ")
tk.Button(root, text="Login", command=login).pack()
# layout
query.pack()
nam_lbl.pack()
val_lbl.pack()
zero_lbl.pack()
root.mainloop()

How to use text file to load data and assign it to a variable?

i am new to python(learner).I created a simple program which asks for username and password and i used getpass()function to hide password
.But i want my program to load username and password from a text file.
#!/usr/bin/env python
import getpass
import os
print (' ')
print (' ')
print ('Please enter username and password in order to continue :')
print (' ')
print (' ')
user = (str(input(' USERNAME : ')))
usr_list = open("usr.txt", "r")
for line in usr_list:
line.strip()
if line == user:
password = getpass.getpass(" PASSWORD : ")
if password == 'root':
os.system("python3 cross.py")
else:
print ('WRONG! Password')
os.system("python3 sec.py")
else:
print ('WRONG! Username')
os.system("python3 sec.py")
now, if i remove text file and open function from code and insert a string like "user1" if user == "user1": it works fine.
You can read data from text file simple:
with open('your_text_file.txt', 'r') as f:
username = f.readline()
password = f.readline()
This is mean that you are open file "your_text_file.txt" for reading ('r' as second parameter) and we read first line, after that we read the next line
This is work if your username and password write in the different line:
your_text_file.txt:
sume_username
verylongandstrongpassword
You can read about read and write file here

Categories