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.
Related
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")
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
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
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()
I am making a quiz in python using the tkinter module and I am stuck on how to create a button that checks to see if the answer is correct or not. But I would put it in a procedure however the question is already in one.
import tkinter as tk
window = tk.Tk()
window.title("6 Questions")
window.geometry("500x150")
score = 0
def inst():
t = tk.Label(window, text="All you need to do is just answer each question with either a '1, 2, 3' or the actual word.")
t.pack()
def start():
root = tk.Tk()
root.title("question 1")
q = tk.Label(root, text="what type of input holds whole numbers")
q.pack()
a = tk.Label(root, text="1.) int")
a.pack()
b = tk.Label(root, text="2.) string")
b.pack()
c = tk.Label(root, text="3.) float")
c.pack()
ans = tk.Entry(root, width=40)
ans.pack()
#here is the button I want to verify the answer
sub = tk.Button(root, text="Submit")
sub.pack()
greet = tk.Label(window, text="Welcome to the 6 Question Quiz.")
greet.pack()
start = tk.Button(window, command=start, text="Start")
start.pack()
instr = tk.Button(window, text="Instructions", command=inst)
instr.pack()
end = tk.Button(window, text="Exit", command=exit)
end.pack()
Create a function that opens when the submit button is clicked and create RadioButtons rather than Labels.
Like this:
def gettingDecision():
if var.get() is 'True':
messagebox.showinfo('Congrats', message='You Are Correct.Score is {}'.format(score))
else:
messagebox.showinfo('Lose', message='You Are Wrong.')
Question1 = ttk.Label(frame1, text='Q.1.Where does a computer add and compare data ?')
Question1.grid(row=1, column=0, sticky=W)
var = StringVar()
Q1A = ttk.Radiobutton(frame1, text='[A] Hard disk', variable=var, value='False1')
Q1A.grid(row=2, column=0, sticky=W)
Q1B = ttk.Radiobutton(frame1, text='[B] Floppy disk', variable=var, value='False2')
Q1B.grid(row=3, column=0, sticky=W)
Q1C = ttk.Radiobutton(frame1, text='[C] CPU chip', variable=var, value='True')
Q1C.grid(row=4, column=0, sticky=W)
Q1D = ttk.Radiobutton(frame1, text='[D] Memory chip', variable=var, value='False3')
Q1D.grid(row=5, column=0, sticky=W)
submit = ttk.Button(frame1, text='Submit', command=gettingDecision)
submit.grid()
Please note that, ideal way to go would be using classes.
You can define a function, inside of a function.
import tkinter as tk
window = tk.Tk()
window.title("6 Questions")
window.geometry("500x150")
score = 0
def inst():
t = tk.Label(window, text="All you need to do is just answer each question with either a '1, 2, 3' or the actual word.")
t.pack()
def start():
def submit():
print (ans.get())
#or do whatever you like with this
root = tk.Tk()
root.title("question 1")
q = tk.Label(root, text="what type of input holds whole numbers")
q.pack()
a = tk.Label(root, text="1.) int")
a.pack()
b = tk.Label(root, text="2.) string")
b.pack()
c = tk.Label(root, text="3.) float")
c.pack()
ans = tk.Entry(root, width=40)
ans.pack()
#here is the button I want to verify the answer
sub = tk.Button(root, text="Submit", command=submit)
sub.pack()
greet = tk.Label(window, text="Welcome to the 6 Question Quiz.")
greet.pack()
startButton = tk.Button(window, command=start, text="Start")
startButton.pack()
instr = tk.Button(window, text="Instructions", command=inst)
instr.pack()
end = tk.Button(window, text="Exit", command=window.destroy)
end.pack()
window.mainloop()