Tkinter GUI window not recognised in other functions - python

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

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 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.

Why doesn't my code print anything?

Why doesn't my code print anything when I press a radiobutton and then the submit button? For example, if I press the "Open Save" radiobutton, leave the entry blank and press submit it should print "test2", but it doesn't print anything no matter what I do.
def Saves():
global saveordelete
saveordelete = 0
global savedname
def openthesave():
saveordelete = 1
def deletethesave():
saveordelete = 2
def opensave():
if saveordelete == 1:
openname = savedname.get() + ".txt"
my_file = Path(openname)
if my_file.is_file():
print("tes1")
else:
print("test2")
elif saveordelete == 2:
openname = savedname.get() + ".txt"
my_file = Path(openname)
if my_file.is_file():
print("test3")
else:
print("test4")
root = Tk()
root.title("Saves")
root.iconbitmap("morseicon.ico")
root.resizable(0,0)
Label(root, text="Name:").grid(row=0, column=0, sticky=W)
savedname = Entry(root, width=20)
savedname.grid(row=0, column=1)
Button(root, text="Submit", width=10, command=opensave, bg="aqua").grid(row=3, column=8)
Label(root, text="Choose kind:").grid(row=1, column=0, sticky=W)
Radiobutton(root, text="Open save", height="1", command=openthesave, value=1).grid(row=2, column=0, sticky=W)
Radiobutton(root, text="Delete save", height="1", command=deletethesave, value=2).grid(row=3, column=0, sticky=W)
root.mainloop()
saveordelete is a local variable in the functions openthesave() and deletethesave(). They do not change the value of the global saveordelete defined in Saves(). Either mark it as global in both functions, or (better) use a class.

Python tkinter quiz

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

Tkinter dynamic button that calls the function selected in a OptionMenu Widget

I would like to know how to create a dynamic button that calls the function selected in a OptionMenu Widget.
In the penultimate line [-2], I substituted "command=daily_return" by "command=var" but it does not work.
Any suggestions?
Best
Working code
from Tkinter import *
import Tkinter
import tkMessageBox
master = Tk()
myvar_1 = IntVar()
myvar_2 = IntVar()
myvar_3 = StringVar()
myvar_4 = IntVar()
myvar_5 = IntVar()
myvar_6 = IntVar()
myvar_7 = IntVar()
#
def daily_return(*args):
print "The start date is ", var.get(), "+", myvar_1.get(),"-", myvar_4.get(), "-", myvar_6.get(), "and the end date is", myvar_2.get(),"-", myvar_5.get(), "-", myvar_7.get(), " for the stock ticker:", myvar_3.get(), "."
def cumulative_return(*args):
print "The start date is ", myvar_1.get(), "the cumulative return."
def value_at_risk(*args):
print "The start date is ", myvar_1.get(), "the value at risk."
Label(master, text="Start Date (DD-MM-YYYY)").grid(row=0)
Label(master, text="End Date (DD-MM-YYYY)").grid(row=1)
Label(master, text="Stock Ticker").grid(row=2)
##
text_entry_1 = Entry(master, textvariable=myvar_1)
text_entry_1.pack()
text_entry_2 = Entry(master, textvariable=myvar_2)
text_entry_2.pack()
text_entry_3 = Entry(master, textvariable=myvar_3)
text_entry_3.pack()
text_entry_4 = Entry(master, textvariable=myvar_4)
text_entry_4.pack()
text_entry_5 = Entry(master, textvariable=myvar_5)
text_entry_5.pack()
text_entry_6 = Entry(master, textvariable=myvar_6)
text_entry_6.pack()
text_entry_7 = Entry(master, textvariable=myvar_7)
text_entry_7.pack()
#
var = StringVar()
var.set('Choose function')
choices = ['cumulative_return', 'daily_return', 'value_at_risk']
option = OptionMenu(master, var, *choices)
option.pack()
##
text_entry_1.grid(row=0, column=1)
text_entry_2.grid(row=1, column=1)
text_entry_3.grid(row=2, column=1)
text_entry_4.grid(row=0, column=2)
text_entry_5.grid(row=1, column=2)
text_entry_6.grid(row=0, column=3)
text_entry_7.grid(row=1, column=3)
option.grid(row=4, column=0)
sf = "Quant Program"
#
def quit():
global root
master.destroy()
#
master.title("Quant Program")
Button(master, text='Quit', command=quit).grid(row=4, column=4, sticky=W, pady=4)
Button(master, text='Show', command=daily_return).grid(row=4, column=1, sticky=W, pady=4)
mainloop( )
Sometimes the simplest solution is Good Enough:
def do_something():
# define a mapping from the choice value to a function name
func_map = {
"daily_choices": daily_choices,
"value_at_risk": value_at_risk,
"cumulative_return": cumulative_return,
}
# using the map, get the function
function = func_map[var.get()]
# call the function
function()
...
Button(..., command=do_something)

Categories