load txt file to listbox using tkinter - python

I just cant make this load button work so that it loads the output.txt file to my listbox. im a first year 160 student with no background in coding and im trying to make this silly phone book as my first "big project" just to get kinda of an idea of what im doing and ive got everything else working besides the loading feature of my output.txt file. forgive my horrible coding im sure it could be a million times better xd
from tkinter import *
win = Tk()
def delete():
select=listbox.curselection()
index=select[0]
listbox.delete(index)
def returnEntry(arg=None):
fname = e1.get()
lname = e2.get()
number = e3.get()
listbox.insert(END, fname+ ' ' + lname+ ' ' + number)
def save():
list1=list(listbox.get(0,END))
f=open("output.txt", "w")
f.writelines(str(list1))
f.close()
def load():
with open("output.txt", "r") as f:
output=f.read()
Label(win, text="First Name").grid(row=0)
Label(win, text="Last Name").grid(row=1)
Label(win, text="Phone Number").grid(row=2)
resultLabel = Label(win, text = "")
resultLabel.grid(row=4, column=1)
resultLabel1 = Label(win, text = "")
resultLabel1.grid(row=4, column=2)
resultLabel2 = Label(win, text = "")
resultLabel2.grid(row=4, column=3)
fname=StringVar()
e1 = Entry(win, textvariable=fname)
lname=StringVar()
e2 = Entry(win, textvariable=lname)
number=StringVar()
e3 = Entry(win, textvariable=number)
scrollbar=Scrollbar(win, orient=VERTICAL)
listbox=Listbox(win, selectmode=EXTENDED, yscrollcommand=scrollbar.set,width=40)
listbox.grid(row=4, columnspan=3)
scrollbar.config(command=listbox)
b1=Button(win, text="Add", command = returnEntry)
b2=Button(win, text="Delete", command=delete)
b3=Button(win, text="Save", command=save)
b4=Button(win, text="load", command=load)
win.bind("<Return>", returnEntry)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
b1.grid(row=3, column=1, sticky=W)
b2.grid(row=3, column=1)
b3.grid(row=3, column=1, sticky=E)
b4.grid(row=3, column=2, sticky=W)
win.mainloop()

Related

How to Encrypt a password to check for a correct login

So today i decided to make a program that tests for correct login and password. When testing for the password i use password_insert.get() == 'Encrypted password', i was able to encrypt my password and got a string that was along the lines of 'ujghtsihjsohjiohfjh', i then inserted that string into the 'encrypted password' but now the password_insert.get() needs to be encrypted using the same method to match it. i thought that using the original method which was using .encrypt would work, so it would look like this password_insert.get.encrypt() but of course that doesn't work, so how am i able to do this?
full code
from tkinter import *
from cryptography.fernet import Fernet
root = Tk()
root.title("Login Tester")
def login1():
if email_insert.get() == 'Test' and password_insert.get() == 'Encrypted password':
print("Success")
root.destroy()
else:
root.destroy()
root2 = Tk()
check_button = Label(root2, text="Fail", font=44).grid(row=0, column=0)
spacer = Label(root2, text=" ").grid(row=1, column=0)
root2.mainloop()
# Def labels
email_label = Label(root, text="Email", font=22)
password_label = Label(root, text="Password", font=22)
# grid labels
email_label.grid(row=0, column=0, padx=28, pady=10)
password_label.grid(row=1, column=0, padx=10, pady=10)
# def text boxes
email_insert = Entry(root, width=35, borderwidth=5)
password_insert = Entry(root, width=35, borderwidth=5, show="*")
# grid text boxes
email_insert.grid(row=0, column=1, columnspan=2)
password_insert.grid(row=1, column=1, columnspan=2)
#def button
login = Button(root, text="Login", command= login1)
login.grid(row=2, column=1)
root.mainloop()

How do i clear a grid

I would like to clear the write email and write password grid when the del button is pressed, and then I can still save new emails and passwords, how do I do this? I tried to create a def clear using grid_slaves, but it erases everything, I want it to delete just write email and write password
from tkinter import *
roots = Tk()
roots.title("Email's save")
roots.geometry("500x500")
e = Entry(roots)
e.grid(row=0, column=1)
e.focus_set()
p = Entry(roots, show="*")
p.grid(row=1, column=1)
p.focus_set()
textEmail = StringVar()
textPassword = StringVar()
def callback():
textEmail.set(textEmail.get() + e.get() + "\n")
textPassword.set(textPassword.get() + p.get() + "\n")
def EmailPassword():
email = Label(roots, text="Email: ",font=('Courier', 14))
email.grid(row=0, sticky=W)
passoword = Label(roots, text="Password: ",font=('Courier', 14))
passoword.grid(row=1, sticky=W)
saved_email = Label(roots, text="Saved Email",font=('Courier', 14))
saved_email.grid(row=15, column=0)
saved_password = Label(roots, text="Password",font=('Courier', 14))
saved_password.grid(row=15, column=15)
write_email = Label(roots, textvariable=textEmail,font=('Courier', 14))
write_email.grid(row=20, column=0)
write_password = Label(roots, textvariable=textPassword,font=('Courier', 14))
write_password.grid(row=20, column=15)
btn_save = Button(roots, text="Save", command= callback)
btn_save.grid(row=10, column=2, sticky=W)
btn_del = Button(roots, text="X", fg="red")
btn_del.grid(row=60, column= 20)
roots.mainloop()
EmailPassword()
The grid is just a single text field with newlines. To clear it, just set the text value to "".
Try this code.
from tkinter import *
roots = Tk()
roots.title("Email's save")
roots.geometry("500x500")
e = Entry(roots)
e.grid(row=0, column=1)
e.focus_set()
p = Entry(roots, show="*")
p.grid(row=1, column=1)
p.focus_set()
textEmail = StringVar()
textPassword = StringVar()
def callback():
textEmail.set(textEmail.get() + e.get() + "\n")
textPassword.set(textPassword.get() + p.get() + "\n")
def clearentries():
e.delete(0, 'end')
p.delete(0, 'end')
def cleargrid():
textEmail.set("")
textPassword.set("")
def EmailPassword():
print ('save')
global lstlabels
email = Label(roots, text="Email: ",font=('Courier', 14))
email.grid(row=0, sticky=W)
passoword = Label(roots, text="Password: ",font=('Courier', 14))
passoword.grid(row=1, sticky=W)
saved_email = Label(roots, text="Saved Email",font=('Courier', 14))
saved_email.grid(row=15, column=0)
saved_password = Label(roots, text="Password",font=('Courier', 14))
saved_password.grid(row=15, column=15)
write_email = Label(roots, textvariable=textEmail,font=('Courier', 14))
write_email.grid(row=20, column=0)
write_password = Label(roots, textvariable=textPassword,font=('Courier', 14))
write_password.grid(row=20, column=15)
btn_save = Button(roots, text="Save", command= callback)
btn_save.grid(row=10, column=2, sticky=W)
btn_del = Button(roots, text="X", fg="red", command= cleargrid) # reset grid
btn_del.grid(row=60, column= 20)
roots.mainloop()
def key(event): # listen for key press
if event.keysym == 'Delete':
clearentries() # clear text boxes
roots.bind_all('<Key>', key)
EmailPassword()
You can use .set("")`` to remove whatever you entered in your Entry``` wigit
Here is a simple example which may help you
from tkinter import *
root=Tk()
#string var
email=StringVar()
def save():
email.set("")
a=Label(root,text='Email').grid(row=0,column=0)
ae=Entry(root,textvar=email,font=("arial 16 bold")).grid(row=0,column=1)
btn=Button(text='Save',command=save).grid(row=1,column=0)
root.mainloop()

Why does this not add?

I've looked other questions and have tried to fix this but I am really struggling with having my code print back the answer.
from tkinter import *
root = Tk()
label1 = Label(root, text="Number 1")
label2 = Label(root, text="Number 2")
labelplus = Label(root, text="+")
label1.grid(row=0, sticky=E)
label2.grid(row=3, sticky=E)
labelplus.grid(row=2, column=1)
entry1_var= StringVar()
entry2_var= StringVar()
entry1 = Entry(root, textvariable= entry1_var)
entry2 = Entry(root, textvariable= entry2_var)
entry1.grid(row=0, column=1)
entry2.grid(row=3, column=1)
first = (entry1_var.get()
second =(entry2_var.get()
def additionStuff(event):
totalNumbers = (first + second)
print(totalNumbers)
button1 = Button(root, text="Add Numbers")
button1.bind("<Button-1>", additionStuff)
button1.grid(row=4, column=1)
root.mainloop()
Why does my function now print back the answer?
You need to call StringVar.get inside of additionStuff:
def additionStuff(event):
first = entry1_var.get()
second = entry2_var.get()
totalNumbers = (float(first) + float(second))
print(totalNumbers)
Otherwise you're getting the value of first and second before the user has had opportunity to enter anything.

Using StringVar data as a list

I've been following this website for a while. It is really helpful. So, thanks for all the useful tips.
I've been searching for this answer for the past two weeks without any success, so now I'm compelled to ask out of total frustration with my current obstacle.
How do you use StringVar as a list?
Basically, I was coding the following program for my wife. The code is pretty messy as it is my first program I've tried to code.
The idea was that I would take 3 variables; password, secret number and website and then do some work on them using if statements and lists to create a unique password.
First problem was that I couldn't restrict the character length of the entry widgets but in the end i solved that but i still want to limit the characters that can be input.
for instance in the website entry box, i want to allow only letters.
If I could convert StringVar to a list, I could do some work with messy if statements to allow only certain characters in each index but everythime i try it says that stringvars cant be used as a list.
I need them as a list to limit the type of characters that can be entered and also so that i can do work on the variables to get the final output.
CODE:
from Tkinter import *
import Tkinter
from PIL import Image, ImageTk
import os
Title= ("Helvetica", 20, "bold", "underline")
Heading= ("Courier", 20, "bold")
Body= ("Courier", 15)
Body1= ("Courier", 15, "bold")
notice= ("Courier", 10)
Body2= ("Courier", 15, "bold", "underline")
root = Tk()
root.title("Koala Series: Encrypter")
root.configure(background="#ffefd5")
root.geometry('{}x{}'.format(510, 600))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1) # not needed, this is the default behavior
root.rowconfigure(1, weight=1)
root.rowconfigure(2, weight=1)
website = StringVar()
Titlemsg = Label(root, text="Koala Encrypter", font=Title, bg="#00FA9A", relief=RAISED,)
Titlemsg.grid( row=7, pady=25, sticky=N+S+E+W)
img1 = ImageTk.PhotoImage(Image.open("koala.jpeg"))
startpic = Label(root, image = img1, relief=RIDGE )
startpic.grid( row=10,pady=25, )
Head = Label(root,anchor=CENTER,text="Welcome to the Koala Encrypter \n\n A Koala series tool that allows you\n\n to Encrypt your passwords \n\n Click \'Start Encrypting\' to continue \n\n", font=Body, bg="#ffefd5", relief=RAISED,)
Head.grid( row=14, pady=25, columnspan=2, sticky=N+S+E+W)
web = Label(root, text="WEBSITE: ", font=Body, bg="#ffefd5", justify=CENTER,)
#website.set("Enter your website here")
entry = Entry(root,textvariable=website , justify=CENTER,relief=SUNKEN,cursor="pencil", takefocus=True )
Notice1 = Label( text="Please only insert the first 5 letters of the website!!",font=notice, bg="#ffefd5", fg="#0000ff",)
passw = Label(root, text="PASSWORD: ", font=Body, bg="#ffefd5", justify=CENTER)
passwordvar= StringVar()
entry1 = Entry(root, textvariable= passwordvar, justify=CENTER,relief=SUNKEN, cursor="pencil", takefocus=True )
Notice= Label(root, text="Your password must only be 5 characters long!!", font=notice, bg="#ffefd5", fg="#0000ff", justify=CENTER)
def callback(event):
if "<0>":
top = Toplevel(bg="#ffefd5")
top.title("Koala Encrypter")
popuptitle = Label(top, text="Your secret number must be between 1 and 9:", font=Body1, fg="red", bg="#ffefd5")
popuptitle.grid(row = 2,column=0, padx=5, pady = 50,sticky=N+S+E+W)
secret = Label(root, text="SECRET NUMBER: ", font=Body, bg="#ffefd5" , justify=CENTER,)
numbervar = StringVar()
entry2 = Entry(root, textvariable=numbervar , justify=CENTER,relief=SUNKEN,cursor="pencil", takefocus=True)
entry2.bind("<0>", callback)
Notice2 = Label(root, text="your secret number must be between 1 and 9!!!", font=notice, bg="#ffefd5", fg="#0000ff", justify=CENTER)
img = ImageTk.PhotoImage(Image.open("Koalalogo.jpg"))
panel = Label(root, image = img, relief=SUNKEN)
correct= Label(root, text="Check the below details \n\n Click \'yes\' if they are correct \n\n Click \'No\' to go back \n\n", font=Body1, bg="#ffefd5")
yourwebsite = Label(root, text="The Website is :", font=Body, bg="#ffefd5")#
website1 = Label(root, font=Body2, bg="#ffefd5",fg= "#00009C", textvariable = website)#
yourpassword = Label(root, text="Your Password is:", font=Body, bg="#ffefd5")
yournumber1= Label(root, font=Body2, bg="#ffefd5",textvariable = numbervar , fg= "#00009C", )
yourpassword1 = Label(root, font=Body2, bg="#ffefd5",textvariable = passwordvar , fg= "#00009C", )
yournumber= Label(root, text="Your Secret Number is:", font=Body, bg="#ffefd5")
def restart():
Titlemsg.grid_forget()
correct.grid_forget()
yourwebsite.grid_forget()
website1.grid_forget()
yourpassword.grid_forget()
yourpassword1.grid_forget()
yournumber.grid_forget()
yournumber1.grid_forget()
panel.grid_forget()
toolbar.grid_forget()
yes.grid_forget()
no.grid_forget()
entry.delete(0,END)
entry1.delete(0,END)
entry2.delete(0,END)
Titlemsg.grid( row=7, pady=25, sticky=N+S+E+W)
startpic.grid( row=10,pady=25, )
Head.grid( row=14, pady=25, columnspan=2, sticky=N+S+E+W)
toolbar.grid( row=21, )
end.grid(column =3, row=1, sticky=N+S+E+W)
begin.grid(column =2, row=1, sticky=N+S+E+W)
def start():
#entry.destroy()
#entry1.destroy()
#entry2.destroy()
toolbar.grid_forget()
Titlemsg.grid_forget()
begin.grid_forget()
Head.grid_forget()
startpic.grid_forget()
web.grid(row=3, column=0, sticky= W+E)
entry.grid( row=3, column=1, padx=50)
passw.grid(row=10, column=0)
Notice1.grid(row=4, sticky=N+S+E+W, columnspan=2)
entry1.grid(row=10, column=1)
Notice.grid(row=11,column=0, columnspan=2,)
secret.grid(row=13, column=0)
entry2.grid( row=13, column=1)
Notice2.grid( row=14,column=0, columnspan=2,)
panel.grid(row=20,columnspan=2, pady=70)
confirm.grid(column =1, row=1)
reset.grid(column =2, row=1)
end.grid(column =3, row=1)
toolbar.grid(row=21, column=0, columnspan=2)
Titlemsg.grid(row=0, column=0, columnspan=2, sticky=E+W)
def Reset():
entry.delete(0,END)
entry1.delete(0,END)
entry2.delete(0,END)
def clear_text():
#entry.destroy()
#entry1.destroy()
#entry2.destroy()
panel.grid_forget()
entry.grid_forget()
entry1.grid_forget()
entry2.grid_forget()
web.grid_forget()
Notice.grid_forget()
passw.grid_forget()
secret.grid_forget()
Notice1.grid_forget()
Notice2.grid_forget()
confirm.grid_forget()
reset.grid_forget()
toolbar.grid_forget()
Titlemsg.grid_forget()
Titlemsg.grid(row=0, column=0, columnspan=2, sticky=E+W)
correct.grid(row=1, column=0, columnspan=2, sticky=E+W)
yourwebsite.grid(row=2,column=0,sticky=E+W, pady=5)
website1.grid(row=2, column=1, padx=65,sticky=E+W, pady=5)
yourpassword.grid(row=4, column=0,sticky=E+W, pady=5)
yourpassword1.grid(row=4, column=1, padx=65,sticky=E+W, pady=5)
yournumber.grid(row=6, column=0,sticky=E+W, pady=5)
yournumber1.grid(row=6, column=1, padx=65,sticky=E+W, pady=5)
panel.grid(row=8, column=0, columnspan=2, pady=50)
toolbar.grid(row=10, column=0, columnspan=2)
yes.grid(column =1, row=1)
no.grid(column =2, row=1)
def popup():
top = Toplevel(bg="#ffefd5")
top.title("Koala Encrypter")
popuptitle = Label(top, text="Your password is:", font=Body1, fg="red", bg="#ffefd5")
popuptitle.grid(row = 2,column=0, padx=5, pady = 50,sticky=N+S+E+W)
pwd= Label(top, font=Body2, text="password", bg="#ffefd5", fg= "#00009C", ) #textvariable = newpassword ,
pwd.grid(row= 2, column=1,sticky=E+W,padx=15)
button = Button(top, text="OK", command=top.destroy, relief=RAISED )
button.grid(column =0,columnspan=2, row=4, sticky=N+S+E+W)
def helpmsg():
top = Toplevel(bg="#ffefd5")
top.title("Koala Encrypter")
popuptitle = Label(top, text="Koala series 1.0 - Koala Encrypter", font=Title, bg="#00FA9A", relief=RAISED,)
popuptitle.grid(row = 2,column=0, padx=5, pady = 50,sticky=N+S+E+W)
pwd= Label(top, font=Body, text="Free software to help you keep your acounts safe", bg="#ffefd5")
pwd.grid(row= 1,sticky=E+W,)
Titlems = Label(top, text="Koala Encrypter", font=Title, bg="#00FA9A", relief=RAISED,)
Titlems.grid( row=0, pady=25, sticky=N+S+E+W)
button = Button(top, text="OK", command=top.destroy, relief=RAISED )
button.grid(column =0,columnspan=2, row=4, sticky=N+S+E+W)
max_len = 5
def on_write(*args):
s = website.get()
if len(s) > max_len:
website.set(s[:max_len])
website.trace_variable("w", on_write)
max_len1 = 5
def on_write(*args):
s = passwordvar.get()
if len(s) > max_len1:
passwordvar.set(s[:max_len1])
passwordvar.trace_variable("w", on_write)
max_len2 = 1
def on_write(*args):
s = numbervar.get()
if len(s) > max_len2:
numbervar.set(s[:max_len2])
numbervar.trace_variable("w", on_write)
toolbar = Frame(root)
reset = Button(toolbar, text="Reset", width=6, command=Reset, cursor="cross", relief=RAISED, takefocus=True )
end = Button(toolbar, text="Quit" ,command=root.destroy, relief=RAISED, cursor="X_cursor", takefocus=True)
end.grid(column =3, row=1, sticky=N+S+E+W)
begin = Button(toolbar, text="Start Encrypting", command=start, relief=RAISED, cursor="star",takefocus=True )
begin.grid(column =2, row=1, sticky=N+S+E+W)
confirm = Button(toolbar, text="Next", command =clear_text, cursor="star", relief=RAISED,takefocus=True )
yes = Button(toolbar, text="Yes", command =popup, cursor="star", relief=RAISED,takefocus=True )
no = Button(toolbar, text="No", command =restart, cursor="pirate", relief=RAISED, takefocus=True )
toolbar.grid( row=21, )
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Restart", command=restart)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.destroy)
helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu, )
helpmenu.add_command(label="About...", command=helpmsg)
app = root
root.mainloop()
# add functionality, fix validation
To restrict the type/number of characters that can be typed into an entry widget, you can use the entry validatecommand. Here is an example to allow only letters and another one to restrict the entry to 4 digits:
from tkinter import Tk, Entry, Label
def only_letters(action, char):
if action == "1":
# a character is inserted (deletion is 0) allow the insertion
# only if the inserted character char is a letter
return char.isalpha()
else:
# allow deletion
return True
def only_numbers_max_4(action, new_text):
if action == "1":
return new_text.isdigit() and len(new_text) <= 4
else:
return True
root = Tk()
# register validate commands
validate_letter = root.register(only_letters)
validate_nb = root.register(only_numbers_max_4)
Label(root, text="Only letters: ").grid(row=0, column=0)
e1 = Entry(root, validate="key", validatecommand=(validate_letter, '%d', '%S'))
# %d is the action code and %S the inserted/deleted character
e1.grid(row=0, column=1)
Label(root, text="Only numbers, at most 4: ").grid(row=1, column=0)
e2 = Entry(root, validate="key", validatecommand=(validate_nb, '%d', '%P'))
# %P is the new content of the entry after the modification
e2.grid(row=1, column=1)
root.mainloop()
For more details on entry validation, see http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html

how to save text into a txt file using python 2.7 using tk

Im using tkinter and I am trying to get text that's entered by a user to be saved into a existing txt file when they click on save, any ideas.
from Tkinter import *
root = Tk()
w1 = Label(root, text="Username")
w1.pack()
e = Entry(root)
e.pack()
w2 = Label(root, text="Password")
w2.pack()
e1 = Entry(root)
e1.pack()
toolbar = Frame(root)
b = Button(toolbar, text="save", width=9)
b.pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)
mainloop()
The simplest way is to create a function that is called when the save button is clicked. Put it near the top of your script and then set it as the button's command.
def save():
text = e.get() + " " + e1.get() + "\n"
with open("text.txt", "a") as f:
f.write(text)
# Snip
b = Button(toolbar, text="save", width=9, command=save)

Categories

Resources