Stopping messagebox from looping the entire textfile after it found a value - python

i created register and login app. I made a messagebox that pops up when it found a value in the textfiles and also when it doesnt find the value. However it keeps looping my entire textfiles so it loops untill it find the value. How do i prevent it form looping? I tried break but it made it stop at 1st row of textfiles. Please ignore the register button, just the login function at the moment.
the textfiles(users) for login info
from tkinter import *
import time
import tkinter.messagebox as tkMessageBox
##3
#### Variable
##3
window = Tk()
window.geometry("600x400")
window.title("Bookloaner")
stud = open("users.txt","r")
logdin = False
username = "admin"
password = "admin123"
stud = open("users.txt","r")
books=[]
books = open("books.txt","r")
##3
#### Define
##3
def closer():
frame.pack_forget()
logframe.pack_forget()
regframe.pack_forget()
extframe.pack_forget()
time.sleep(0.1)
####2
# FRAMES
####2
logframe=Frame(window)
regframe=Frame(window)
extframe=Frame(window)
def Login():
closer()
def Chek():
for line in open("users.txt", "r").readlines():
loginn_info= line.split()
if name.get() == loginn_info[1] and passwd.get() == loginn_info[2]:
tkMessageBox.askokcancel("System","logged",)
else:
tkMessageBox.askokcancel("System","Error",)
frame.pack_forget()
conf = StringVar()
mesg=Entry(logframe, width=30,textvariable=conf,fg="#900",state="readonly",relief=FLAT)
mesg.grid(row=0,column=2)
labname=Label(logframe,text="What is your name?")
labname.grid(row=1, column=1, sticky=E)
name=StringVar()
entname=Entry(logframe, textvariable=name)
entname.grid(row=1, column=2, sticky=W)
labpass=Label(logframe,text="What is your password?")
labpass.grid(row=2, column=1, sticky=E)
passwd=StringVar()
entpass=Entry(logframe, textvariable=passwd)
entpass.grid(row=2, column=2, sticky=W)
checkbtn = Button(logframe, text="Login", fg="#fff", bg="#00f", command=Chek)
checkbtn.grid(row=3,column=2, sticky=E)
logframe.pack()
def Register():
def Chek():
for i in stud.readlines():
i.rstrip("\n")
i = i.split(":")
print(i)
if username in i[0]:
if password in i[1]:
print("logged in!")
break
else: print("wrong username or password")
else: print("User doesn't exist.")
frame.pack_forget()
logframe=Frame(window)
labname=Label(logframe,text="What is your name?")
labname.grid(row=1, column=1, sticky=E)
entname=Entry(logframe)
entname.grid(row=1, column=2, sticky=W)
labpass=Label(logframe,text="What is your password?")
labpass.grid(row=2, column=1, sticky=E)
entpass=Entry(logframe)
entpass.grid(row=2, column=2, sticky=W)
checkbtn = Button(logframe, text="Register", fg="#fff", bg="#090", command=Chek)
checkbtn.grid(row=3,column=2, sticky=E)
logframe.pack()
def Exit():
window.quit()
exit()
def Getbook():
closer()
def Chek():
firstnaem = firstnaem.rstrip("\n")
lastnaem = books.readline().rstrip("\n")
books += [[firstnaem,lastnaem]]
for i in books.readline():
print(i[0])
extframe = Frame(window, height=400, width=600)
bname=StringVar()
leftframe=LabelFrame(extframe, height=400, width=300)
Label(leftframe, text="Get",font="25").place(y=0,x=0)
Label(leftframe, text="Book ID").place(y=30,x=10)
nr=Entry(leftframe, width=45).place(y=50,x=10)
Label(leftframe, text="Book Name").place(y=70,x=10)
Entry(leftframe, textvariable=bname, width=45,state="readonly",).place(y=90,x=10)
Button(leftframe, text="Get", width=38, height=10, bg="yellow", command=Chek).place(y=121,x=9)
leftframe.place(y=0,x=1)
rightframe=LabelFrame(extframe, height=400, width=300)
Label(rightframe, text="Give",font="25").place(y=0,x=0)
rightframe.place(y=0,x=300)
extframe.place(y=0,x=0)
##3
#### Start
##3
frame = Frame(window, height=400, width=600)
welcom=Label(frame,text="Welcome to Book Extange v1",font="50")
welcom.grid(row=0,column=2)
button1 = Button(frame,text="Login",font="25",width="10",height="3",bg="#00f",fg="white",command=Login)
button1.grid(row=1,column=2, sticky=W)
button2 = Button(frame,text="Register",font="25",width="10",height="3",bg="#090",fg="white",command=Register)
button2.grid(row=1,column=2, sticky=E)
frame.pack()
closebtn = Button(window, text="Close", bg="red", command=Exit)
closebtn.place(x=560)
##3
#### DROP DOWN
##3
menubar = Menu(window)
navmenu= Menu(menubar, tearoff=0)
navmenu.add_command(label="Exit",command=Exit)
navmenu.add_command(label="Home")
navmenu.add_command(label="Login", command=Login)
navmenu.add_command(label="Register", command=Register)
navmenu.add_separator()
menubar.add_cascade(label="Menu", menu=navmenu)
navmenu.add_command(label="Extange",command=Getbook)
window.config(menu=menubar)
window.mainloop()

You need to add break after the line tkMessageBox.askokcancel("System","logged",). Also the else block should be in same indentation of the for line.
Below is the modified Chek():
def Chek():
for line in open("users.txt", "r").readlines():
loginn_info = line.split()
if name.get() == loginn_info[1] and passwd.get() == loginn_info[2]:
tkMessageBox.askokcancel("System", "logged")
break # break out the loop
else:
# credential not found
tkMessageBox.askokcancel("System", "Error")

Related

How do I automatically notify a user that they forgot to select an action?

I'm creating a login system, but I'm having a bug that I don't know how to handle, the situation is this: I want every user to be able to choose between using encryption and not using encryption. For example, a person has entered the correct login information, but the person has forgotten to select the message type, and when the person presses the Enter button, they receive an error that they forgot to select the message type. How do I implement this? Code below:
from tkinter import messagebox
from tkinter import *
window = Tk()
window.title('Login')
window.geometry('320x200')
window.resizable(True, True)
name = StringVar()
password = StringVar()
def crypt():
r = (lis.get(lis.curselection()))
c = (lis.get(lis.curselection()))
string_name = name.get()
string_password = password.get()
#r = (lis.get(lis.curselection()))
#c = (lis.get(lis.curselection()))
if string_name == 'John':
if string_password == '6789':
if r == 'Use encrypted':
window.after(1000, lambda: window.destroy())
print('Hello.')
if string_name == 'John':
if string_password == '6789':
if r == 'Use decrypted':
window.after(1000, lambda: window.destroy())
print('Hello bro!')
if string_name not in 'John':
messagebox.showerror('Error', 'Error')
elif string_password not in '6789':
messagebox.showerror('Error', 'Error')
elif r not in r:
messagebox.showerror('Error', 'Oops, please crypt message') #This Error
elif string_name == 'John':
messagebox.showerror('Error', 'Error')
elif string_password == '6789':
messagebox.showerror('Error', 'Error')
entry = Entry(window, textvariable=name, width=10)
entry.grid(column=1, pady=7, padx=4)
label = Label(window, text='Enter name: ')
label.grid(row=0, padx=1)
entry1 = Entry(window, textvariable=password, width=10, show='*')
entry1.grid(column=1, pady=7, padx=2)
label1 = Label(window, text='Enter password: ')
label1.grid(row=1, padx=1)
listbox = Listbox(window, selectmode=SINGLE, width=12, height=2)
listbox.grid(column=1, row=2, pady=7, padx=2)
r = ['Use encrypted']
c = ['Use decrypted']
lis = Listbox(window, selectmode=SINGLE, width=10, height=2)
lis.grid(column=1, row=2, pady=7, padx=2)
for i in r:
lis.insert(END, i)
for i in c:
lis.insert(END, i)
label_crypto = Label(window, text='Encrypted/decrypted message: ', bg='black', fg='red')
label_crypto.grid(row=2)
button = Button(window, text='Enter', command=crypt)
button.grid(pady=30)
window.mainloop()
As suggested in my comment, improving the names of your variables will better allow you to distinguish between them.
The below code, uses a try-catch block to detect that the user hasn't selected an item from the list box. Tkinter will throw an error if you try to get the selected item form a list when one hasn't been selected.
from tkinter import messagebox
from tkinter import *
import _tkinter
window = Tk()
window.title('Login')
window.geometry('320x200')
window.resizable(True, True)
name = StringVar()
password = StringVar()
def crypt():
try:
user_encryption_selection = (encryption_listbox.get(encryption_listbox.curselection()))
except _tkinter.TclError:
messagebox.showerror('Error','User has not selected an encryption type')
return
string_name = name.get()
string_password = password.get()
if string_name == 'John':
if string_password == '6789':
if user_encryption_selection == 'Use decrypted':
window.after(1000, lambda: window.destroy())
print('Hello bro!')
else:
messagebox.showerror('Error', 'Error Password')
else:
messagebox.showerror('Error', 'Invalid Username')
entry = Entry(window, textvariable=name, width=10)
entry.grid(column=1, pady=7, padx=4)
label = Label(window, text='Enter name: ')
label.grid(row=0, padx=1)
entry1 = Entry(window, textvariable=password, width=10, show='*')
entry1.grid(column=1, pady=7, padx=2)
label1 = Label(window, text='Enter password: ')
label1.grid(row=1, padx=1)
listbox = Listbox(window, selectmode=SINGLE, width=12, height=2)
listbox.grid(column=1, row=2, pady=7, padx=2)
encryption_options = ['Use encrypted','Use decrypted']
encryption_listbox = Listbox(window, selectmode=SINGLE, width=10, height=2)
encryption_listbox.grid(column=1, row=2, pady=7, padx=2)
for i in encryption_options:
encryption_listbox.insert(END, i)
label_crypto = Label(window, text='Encrypted/decrypted message: ', bg='black', fg='red')
label_crypto.grid(row=2)
button = Button(window, text='Enter', command=crypt)
button.grid(pady=30)
window.mainloop()
I've also removed some un-necessary code. You should aim to only check the username/password/encryption values once rather than multiple times in separate if/elif/else conditions

How can I view and edit a txt using tkinter python

Is there a method to add a button where it opens the savefile.txt and lets me edit it while using Tkinter?
My current method is just saving the file and manually opening my txt
Here is my code:
from tkinter import *
from MailSaverFunctions import *
def quitApp():
errmsg = tkinter.messagebox.askquestion("Quit", "Save Before quitting")
if errmsg == "yes":
exit(-1)
elif errmsg == "no":
pass
else:
pass
def SavingInput():
category = categoryEntry.get()
Mail = mailEntry.get()
password = passwordEntry.get()
filewrite = open("SaveFile.txt", "a")
filewrite.write(category + "----" + Mail + "----" + password+"\n")
filewrite.close()
categoryEntry.delete(0, END)
mailEntry.delete(0, END)
passwordEntry.delete(0, END)
root = Tk()
root.title("MailSaver")
savepic = PhotoImage(file="save.png")
quitpic = PhotoImage(file="close.png")
startlbl = Label(root, text="Mail saver, password saver, in addition to categpries, Also organized!! ")
lblcategory = Label(root, text="Category", bd=1, relief=SUNKEN, fg="red")
lblmail = Label(root, text="Mail", bd=1, relief=SUNKEN)
lblpassword = Label(root, text="Password", bd=1, relief=SUNKEN)
categoryEntry = Entry(root)
mailEntry = Entry(root)
passwordEntry = Entry(root)
savebtn = Button(root, image=savepic, command=SavingInput)
quitbtn = Button(root, image=quitpic, command=quitApp)
lblcategory.grid(row=1, column=3, sticky=E)
lblmail.grid(column=3, row=2, sticky=E)
lblpassword.grid(column=3, row=3, sticky=E)
categoryEntry.grid(row=1, column=4)
mailEntry.grid(row=2, column=4)
passwordEntry.grid(row=3, column=4)
savebtn.grid(row=4, column=3)
quitbtn.grid(row=4, column=4)
lblcategory.configure(font="70")
lblmail.configure(font="100")
lblpassword.configure(font="85")
root.mainloop()
just need to make a viewing window and a editing window to edit infile credintals.

How do I fix a name error when I ask for a value before it is defined no matter how it's arranged?

I'm trying to make a small login command that I'll edit to change "lbl3", but for now this is what I have. It's rough, and I'm fairly sure that there are more issues in this than just a name error. That's all I can really come up with in terms of details I'm afraid, as that really is my only goal. I just want to see if there's anything I can do to fix this name error, and stackoverflow isn't letting me post this question without adding more details.
from tkinter import *
window = Tk()
window.title("Welcome to Repl.it")
window.geometry('480x270')
lbl = Label(window, text="Username")
lbl.grid(column=0, row=0)
lbl2 = Label(window, text="Password")
lbl2.grid(column=0, row=1)
lbl3 = Label(window, text="Hidden")
lbl3.grid(column=1, row=10)
lbl3['foreground']="red"
lbl3['width']=20
txt = Entry(window,width=15)
txt.grid(column=1, row=0)
txt2 = Entry(window,width=15)
txt2.grid(column=1, row=1)
btn = Button(window, text="Login", command = login())
btn.grid(column=2, row=7)
btn2 = Button(window, text="Create Account")
btn2.grid(column=0, row=7)
users = { "theatrechick25" : "2Bornot2B", "soccerGuy2024" : "getYourKick$"}
realusers = []
pwds = []
def login():
for x in users:
realusers.append(str(x))
print(realusers)
for x in users:
pwds.append(users[x])
print(pwds)
user = txt.get()
pwd = txt2.get()
if(user in realusers):
print("succeed")
if(pwd in users):
print("Logged in!")
else:
print("failed")
else:
print("failed")
window.mainloop()
Try this:
from tkinter import *
def login():
for x in users:
realusers.append(str(x))
print(realusers)
for x in users:
pwds.append(users[x])
print(pwds)
user = txt.get()
pwd = txt2.get()
if user in realusers:
print("succeed")
if pwd in users:
print("Logged in!")
else:
print("failed")
else:
print("failed")
window = Tk()
window.title("Welcome to Repl.it")
window.geometry("480x270")
lbl = Label(window, text="Username")
lbl.grid(column=0, row=0)
lbl2 = Label(window, text="Password")
lbl2.grid(column=0, row=1)
lbl3 = Label(window, text="Hidden")
lbl3.grid(column=1, row=10)
lbl3['foreground']="red"
lbl3['width']=20
txt = Entry(window,width=15)
txt.grid(column=1, row=0)
txt2 = Entry(window,width=15)
txt2.grid(column=1, row=1)
btn = Button(window, text="Login", command=login)
btn.grid(column=2, row=7)
btn2 = Button(window, text="Create Account")
btn2.grid(column=0, row=7)
users = {"theatrechick25" : "2Bornot2B", "soccerGuy2024" : "getYourKick$"}
realusers = []
pwds = []
window.mainloop()
I changed command=login() to command=login so it doesn't get executed before you press the button. Also I moved the definition of login to the top of the code otherwise you will get an error.

Tkinter GUI window not recognised in other functions

I am making a simple program that saves someone's name and their email address in a file. I am coding in python idle. My code is:
import random
from tkinter import *
num = (random.randint(1,3))
NOSa = open("CN.txt", "r")
NOS = (NOSa.read())
NOSa.close()
NOSa = open("CN.txt", "w")
if num == ("1"):
NOS = NOS + "a"
elif num == ("2"):
NOS = NOS + "v"
else:
NOS = NOS + "x"
NOSa.write(NOS)
NOSa.close()
def efg():
window2.destroy()
window2.mainloop()
exit()
def abc():
name = entry.get()
email = entry2.get()
window.destroy()
window2 = Tk()
window2.title("OP")
OT = Text(window2, width=30, height=10, wrap=WORD, background="yellow")
OT.grid(row=0, column=0, sticky=W)
OT.delete(0.0, END)
MT = "We have logged your details " + name
MT2 = ". We have a file saved called " + NOS
MT3 = ". Go check it out!"
OT.insert(END, MT)
OT.insert(END, MT2)
OT.insert(END, MT3)
new_file = open(NOS, "a")
new_file.write("This is ")
new_file.write(name)
new_file.write(" email address.")
new_file.write(" ")
new_file.write(email)
button2 = Button(window2, text="OK", width=5, command=efg)
button2.grid(row=1, column=0, sticky=W)
window.mainloop()
window2.mainloop()
window = Tk()
window.title("EN")
label = Label(window, text="Enter your name: ")
label.grid(row=0, column=0, sticky=W)
entry = Entry(window, width=20, bg="light green")
entry.grid(row=1, column=0, sticky=W)
label2 = Label(window, text="Enter your email address: ")
label2.grid(row=2, column=0, sticky=W)
entry2 = Entry(window, width=25, bg="light green")
entry2.grid(row=3, column=0, sticky=W)
button = Button(window, text="SUBMIT", width=5, command=abc)
button.grid(row=4, column=0, sticky=W)
window.mainloop()
When I run the code my first 2 boxes appear and run their code perfectly. However, when I click the button 'OK' I get this error:
NameError: name 'window2' is not defined
I use python-idle.
You may make windows2 global
window2 = None
def efg():
global window2
and later
def abc():
global window2

How to attach Python code to exe file

I made a login panel, but i don't know, how to attach code to files,
for example, if i run a .exe file, it runs my code first, and if the entries are filled correctly, the .exe file runs.
My code:
from tkinter import *
import tkinter.messagebox
import os`
username = 'Zsolti'
password = 'zsoltika2005'
def WindowVariables():
global UsernameE
global PasswordE
def CheckLogin():
if UsernameE.get() == username and PasswordE.get() == password:
tkinter.messagebox.showinfo('Login', 'Successfully logged in as:
Zsolti')
else:
tkinter.messagebox.showinfo('Login', 'Login failed')
window = Tk()
MainFrame = Frame(width=110, height=40)
MainFrame.grid()
window.title('Login Panel')
UsernameL = Label(window, text='Enter username')
UsernameL.grid(row=0, column=0, sticky='e')
PasswordL = Label(window, text='Enter password')
PasswordL.grid(row=1, column=0, sticky='e')
UsernameE = Entry(window, textvariable=username)
UsernameE.grid(row=0, column=1, sticky='w')
PasswordE = Entry(window, show='*', textvariable=password)
PasswordE.grid(row=1, column=1, sticky='w')
LoginButton = Button(window, text='Login!', command=CheckLogin)
LoginButton.grid(row=2, columnspan=2)
window.mainloop()
This should work for you, when it logs on correctly, it will call the other exe file, then hopefully terminate the login window,
from tkinter import *
import tkinter.messagebox
import subprocess
import sys
username = 'Zsolti'
password = 'zsoltika2005'
def WindowVariables():
global UsernameE
global PasswordE
def CheckLogin():
if UsernameE.get() == username and PasswordE.get() == password:
tkinter.messagebox.showinfo('Login', 'Successfully logged in as: Zsolti')
subprocess.Popen([r"Important File Path.exe"])
sys.exit()
else:
tkinter.messagebox.showinfo('Login', 'Login failed')
window = Tk()
MainFrame = Frame(width=110, height=40)
MainFrame.grid()
window.title('Login Panel')
UsernameL = Label(window, text='Enter username')
UsernameL.grid(row=0, column=0, sticky='e')
PasswordL = Label(window, text='Enter password')
PasswordL.grid(row=1, column=0, sticky='e')
UsernameE = Entry(window, textvariable=username)
UsernameE.grid(row=0, column=1, sticky='w')
PasswordE = Entry(window, show='*', textvariable=password)
PasswordE.grid(row=1, column=1, sticky='w')
LoginButton = Button(window, text='Login!', command=CheckLogin)
LoginButton.grid(row=2, columnspan=2)
window.mainloop()

Categories