Why doesn't my code print anything? - python

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.

Related

Passing variables through classes and using .get() in Tkinter to find users input

class Menu():
def __init__(self):
pass
def menuWindow(self):
menu = Tk()
menu.title("Menu")
menu.geometry("300x250")
menuFrame = Frame(menu)
menuFrame.pack()
menu = Menu()
menuLabel = Label(menuFrame, font="Helvetica 18 bold", text="MENU")
menuLabel.grid(row=0, column=0, sticky=W)
cDirF = TaskWindowMaker()
cDir = Button(menuFrame, text="Create Directory", command=cDirF.cDirWindow, height=2,width=20)
cDir.grid(row=2, column=0, sticky=W)
cProfF = TaskWindowMaker()
cProf = Button(menuFrame, text="Create Profiles", command=cProfF.cProfWindow, height=2,width=20)
cProf.grid(row=3, column=0, sticky=W)
dProfF = TaskWindowMaker()
dProf = Button(menuFrame, text="Delete Profiles", command=dProfF.dProfWindow, height=2,width=20)
dProf.grid(row=6, column=0, sticky=W)
mSenderF = TaskWindowMaker()
mSender = Button(menuFrame, text="Make Sender", command=mSenderF.mSenderWindow, height=2,width=20)
mSender.grid(row=8, column=0, sticky=W)
sendParcelF = TaskWindowMaker()
sParcel = Button(menuFrame, text="Send Parcel", command=sendParcelF.sendParcelWindow, height=2,width=20)
sParcel.grid(row=10, column=0, sticky=W)
class ProfileDeveloper(object):
def __init__(self,):
pass
def create_folder_profiles(self):
global directoryNamecProfWindow
y = False
while y == False:
path = os.getcwd()
print(path)
y = numbercProfWindow.get()#int(input("Number of profiles: "))
print(y)
#y = int(y)
p = os.getcwd()+("\profiles")#Reading number file in profiles
n = ("number")
d = os.path.join(p,n)
try:
dirName = directoryNamecProfWindow.get()#input("Directory name :")
print(dirName+"OO")
path = os.getcwd()+("\profiles")
folderDir = os.path.join(path, dirName)
with open(folderDir+"profile.txt","x") as f:
print("Opened.")
except FileNotFoundError:
print("File not found.")
except FileExistsError:
messagebox.showerror("Error","File already exists.")
for a in range(y):
with open(d+".txt","r") as z:
num = z.read()
num = int(num)
newNum = (int(num)+1)
numProf = ("profile"+str(newNum))
with open(d+".txt","w") as file:
file.write(str(newNum))
path = os.getcwd()+("\profiles")
folderDir = os.path.join(path, dirName,numProf)
with open(folderDir+".txt","x") as f:
print("Created '"+numProf+"'.")
y = True
#except:
print("Saved to "+folderDir+"\n")
class TaskWindowMaker(object):
def __init__(self):
pass
def cProfWindow(self):
global numbercProfWindow
cProf = Tk()
cProf.title("Create Profiles")
cProf.geometry("300x250")
cProfFrame = Frame(cProf)
cProfFrame.pack()
titleLabel = Label(cProfFrame, font="Helvetica 18 bold", text="Create Profiles")
titleLabel.grid(row=0, column=0, sticky=W)
menuLabel = Label(cProfFrame, text="Folder Name")
menuLabel.grid(row=1, column=0, sticky=W)
directoryNamecProfWindow = StringVar()
cDirEntry = Entry(cProfFrame, textvariable=directoryNamecProfWindow)
cDirEntry.grid(row=1, column=1, sticky=W)
menuLabel = Label(cProfFrame, text="Number of Profiles")
menuLabel.grid(row=2, column=0, sticky=W)
numbercProfWindow = StringVar()
cDirEntry = Entry(cProfFrame, textvariable=numbercProfWindow)
cDirEntry.grid(row=2, column=1, sticky=W)
cProfF = ProfileDeveloper(directoryNamecProfWindow)
cDir = Button(cProfFrame, text="Enter", command=cProfF.create_folder_profiles, height=2,width=20)
cDir.grid(row=3, column=0, sticky=W)
start = Menu()
start.menuWindow()
This is my code. I'm opening multiple Windows. Then when I enter in an input box in
numbercProfWindow = StringVar()
cDirEntry = Entry(cProfFrame, textvariable=numbercProfWindow)
cDirEntry.grid(row=2, column=1, sticky=W)
I'm then using the button:
cProfF = ProfileDeveloper(directoryNamecProfWindow)
cProf = Button(cProfFrame, text="Enter", command=cProfF.create_folder_profiles, height=2,width=20)
cProf.grid(row=3, column=0, sticky=W)
To send the input to ProfileDeveloper.create_folder_profiles
When it's sent to ProfileDeveloper.create_folder_profiles the program doesn't recognise the input, as in it's not '.get()ing it'.
I'm quite new so don't know how to pass variables between different functions and using the .get() function or global variables.
The main aim of the program is creating a profiles (txt files) in a specified folder. Instead of it being a script in shell I'm trying to add a Tkinter GUI.
Hopefully this explains it as I've asked before and people just get too confused. There's still a lot of code which I don't show but the confusion between passing variables continues throughout the code so not sure. The code was really long and just running in Shell then I added the Tkinter GUI and it's complicated it all by doubling variables and now this, so any help is greatly appreciated.
Thanks :)
Does this example help You understand better what You can do:
from tkinter import Tk, Entry, Button
root = Tk()
class UserInput:
def __init__(self, master):
self.master = master
self.entry = Entry(self.master)
self.entry.pack()
self.button = Button(self.master, text='Submit', command=self.submit)
self.button.pack()
def submit(self):
entry_var = self.entry.get()
print(entry_var)
user_input = UserInput(root)
root.mainloop()

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 call bind function more than once in tkinter.

I want to print something on a label whenever user inputs a space. But my code only prints a line when space is entered first time and not after that.
Here is my code:
from tkinter import *
#LOOP_ACTIVE = True
def func1(self):
lsum["text"] = "space entered"
#root.after(0, func1)
root = Tk()
T = Text(root, height=20, width=30)
T.pack(side=RIGHT)
T.grid(row=0, column=1)
T.insert(END, "Just a text Widget\nin two lines\n")
v = IntVar()
a=Radiobutton(root, text="unigram", variable=v, value=1).grid(column=0,row=0)
b=Radiobutton(root, text="bigram", variable=v, value=2).grid(column=0,row=1)
c=Radiobutton(root, text="trigram", variable=v, value=2).grid(column=0,row=2)
T.bind("<space>",func1)
lsum = Label(root)
lsum.grid(row=0, column=2, sticky=W, pady=4)
root.mainloop()
Please Help!
Just added a counter, for you to see that your code works
from tkinter import *
#LOOP_ACTIVE = True
count = 1
def func1(self):
global count
count += 1
lsum["text"] = "space entered" + str(count)
#root.after(0, func1)
root = Tk()
T = Text(root, height=20, width=30)
T.pack(side=RIGHT)
T.grid(row=0, column=1)
T.insert(END, "Just a text Widget\nin two lines\n")
v = IntVar()
a=Radiobutton(root, text="unigram", variable=v, value=1).grid(column=0,row=0)
b=Radiobutton(root, text="bigram", variable=v, value=2).grid(column=0,row=1)
c=Radiobutton(root, text="trigram", variable=v, value=2).grid(column=0,row=2)
T.bind("<space>",func1)
lsum = Label(root)
lsum.grid(row=0, column=2, sticky=W, pady=4)
root.mainloop()

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