How to attach Python code to exe file - python

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()

Related

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

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")

how to add admin priviledge with tkinter

I’m coding a database management app with python tkinter packages. This API is on a NAS (network attached storage). So the users can open it from a connection and make modifications in real time.
I want to give some privilege for admin users. That means if a users log in the app, they can tick and fill entry box which is disabled for normal users.
How to do it?
Here is my try:
from tkinter import *
import tkinter as tk
from tkinter import ttk
#Initialisation
root=Tk()
root.title("Test")
#Tab creation
my_tab=ttk.Notebook(root)
my_tab.pack(expand=True, fill=tk.BOTH)
#Tab name and their creation
frames=[]
nom_des_onglets=["Main", "First tab", "Second tab"]
def admin():
global longentrie
win=Toplevel()
longentrie = StringVar()
password_msg = tk.Label(win,text="Enter password for administrator privileges")
password_msg.pack()
password_entries = tk.Entry(win,textvariable=longentrie)
password_entries.pack()
tk.Button(win,text='Enter', command=admin_privilege).pack()
def admin_privilege():
global login_value
password_admin = longentrie.get()
if password_admin == 'good':
login_value=1
else:
login_value=0
for i in range(3):
frame=ttk.Frame(my_tab) # add tab
frame.pack(fill="both")
frames.append(frame)
my_tab.add(frames[i], text=nom_des_onglets[i])
#Login button
login=tk.Button(frames[0],text="login", command=admin)
login.pack()
#special priviledge
var1 = tk.IntVar()
ts = [tk.StringVar() for _ in range(17)]
lbl7 = tk.Checkbutton(frames[1], text='Text',variable=var1, onvalue=1,offvalue=0, bg='#ececec', state='disabled')
lbl7.grid(row=0, column=0, padx=5, pady=3)
lbl1=tk.Label(frames[1], text="Name")
lbl1.grid(row=2, column=0, padx=5, pady=3)
ent7=Entry(frames[1], textvariable=ts[6])
ent7.grid(row=2, column=1, padx=5, pady=3,sticky="nsew")
lbl8=tk.Label(frames[1], text="Age")
lbl8.grid(row=3, column=0, padx=5, pady=3)
ent8=Entry(frames[1], textvariable=ts[7],state='disabled')
ent8.grid(row=3, column=1, padx=5, pady=3,sticky="nsew")
if login_value == 1:
lbl7.configure(state='normal')
ent8.configure(state='normal')
root.mainloop()
Here's an example where entering the right password does correctly change the disabled state of those two fields.
This could be refactored to be a lot less messy (better variable naming for one), but it's a start:
import tkinter as tk
from tkinter import ttk
is_admin = False
def setup_ui():
lbl7.configure(state=("normal" if is_admin else "disabled"))
ent8.configure(state=("normal" if is_admin else "disabled"))
def do_login_window():
def admin_privilege():
global is_admin
if password_var.get() == "good":
is_admin = True
setup_ui()
login_win.destroy() # Close the login box
login_win = tk.Toplevel()
password_var = tk.StringVar()
password_msg = tk.Label(login_win, text="Enter password for administrator privileges")
password_msg.pack()
password_entries = tk.Entry(login_win, textvariable=password_var)
password_entries.pack()
tk.Button(login_win, text="Enter", command=admin_privilege).pack()
# Initialisation
root = tk.Tk()
root.title("Test")
# Tab creation
my_tab = ttk.Notebook(root)
my_tab.pack(expand=True, fill=tk.BOTH)
frames = []
for name in ["Main", "First tab"]:
frame = ttk.Frame(my_tab)
frame.pack(fill="both")
frames.append(frame)
my_tab.add(frame, text=name)
# Login button
login_frame = frames[0]
login = tk.Button(login_frame, text="login", command=do_login_window)
login.pack()
# special priviledge
data_frame = frames[1]
var1 = tk.IntVar()
ts = [tk.StringVar() for _ in range(17)]
lbl7 = tk.Checkbutton(
data_frame, text="Text", variable=var1, onvalue=1, offvalue=0, bg="#ececec"
)
lbl7.grid(row=0, column=0, padx=5, pady=3)
lbl1 = tk.Label(data_frame, text="Name")
lbl1.grid(row=2, column=0, padx=5, pady=3)
ent7 = tk.Entry(data_frame, textvariable=ts[6])
ent7.grid(row=2, column=1, padx=5, pady=3, sticky="nsew")
lbl8 = tk.Label(data_frame, text="Age")
lbl8.grid(row=3, column=0, padx=5, pady=3)
ent8 = tk.Entry(data_frame, textvariable=ts[7])
ent8.grid(row=3, column=1, padx=5, pady=3, sticky="nsew")
setup_ui() # Will be called after logging in too
root.mainloop()

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.

Update Label in Tkinter when calling function

I have a Tkinter GUI and I would like to update the status of the script in a Label, writing which function is being called, but I am having problems with that.
I have already seen many answers on here, but still I cant come to a solution. This is the part of the code that I am working on:
run_script(username, password):
text = StringVar()
text.set('')
l=Label(master, text=text, fg='blue')
l.grid(row=6) #I would like the Label in the row 6
l.pack()
text.set('calling my function1')
my_file.my_function1(username, password)
text.set('calling my function2')
my_file.my_function2()
master = Tk()
username = Entry(master, name='username', width=30)
password = Entry(master, name='password', show='*', width=30)
username.grid(row=0, column=1, padx=10, pady=(10,2))
password.grid(row=1, column=1, padx=10, pady=2)
def call_report(username, password):
run_script(username, password)
Button(master, text='start script',
command= lambda:call_report(username.get(), password.get(),)).grid(row=6, column=1, sticky=W, pady=10)
mainloop()
The program run perfectly, just the label is not updated. Thanks
here is one way to do it, using the keyword argument textvariable:
import tkinter as tk
def run_script(username, password):
text = tk.StringVar()
text.set('')
lab = tk.Label(master, textvariable=text, fg='blue')
lab.grid(row=6)
text.set('calling my function1')
# call functions here
def call_report(username, password):
run_script(username, password)
if __name__ == '__main__':
master = tk.Tk()
username = tk.Entry(master, name='username', width=30)
password = tk.Entry(master, name='password', show='*', width=30)
username.grid(row=0, column=1, padx=10, pady=(10,2))
password.grid(row=1, column=1, padx=10, pady=2)
button = tk.Button(master, text='start script', command=lambda: call_report(username.get(), password.get(),))
button.grid(row=6, column=1, sticky=tk.W, pady=10)
master.mainloop()
Note:
The use of pack and grid geometry managers in the same widget is not encouraged.
Please import tkinter as tk: adding tk. is a small price to keep the namespace clean.
This is my solution that can be used as example:
from Tkinter import *
from time import sleep
def run_script():
text = StringVar()
l = Label(master, textvariable=text, fg='blue').grid(row=6)
text.set('calling my function1')
master.update()
sleep(2)
text.set('end of function1')
def call_report():
run_script()
if __name__ == '__main__':
master = Tk()
username = Entry(master, name='username', width=30)
password = Entry(master, name='password', show='*', width=30)
username.grid(row=0, column=1, padx=10, pady=(10,2))
password.grid(row=1, column=1, padx=10, pady=2)
button = Button(master, text='start script', command=lambda: call_report())
button.grid(row=6, column=1, sticky=W, pady=10)
master.mainloop()
I've changed text to textvariable in Label, and I added master.update(). In this way it force the GUI to redraw. Just to test if the GUI was changing, I tested with sleep. It is possible to update more time (for example before calling a function).

Categories