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)
Related
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 don't know how to return or print result to entry widget. I've tried to add code on the res function, but it still doesn't return the result that I want.
import tkinter as tk
from tkinter import *
win = tk.Tk()
win.title("Test")
win.configure(background='black')
enternumber = Label(win, text="Enter Number")
enternumber.grid(column=0, row=0)
var1 = IntVar()
txtenternumber = Entry(win, width=20, textvariable=var1)
txtenternumber.grid(column=1, row=0)
enternumber = Label(win, text="Enter Number")
enternumber.grid(column=0, row=1)
var2 = IntVar()
txtenternumber = Entry(win, width=20, textvariable=var2)
txtenternumber.grid(column=1, row=1)
def res():
result = var1.get()*var2.get()
#here the code i added
resultentry.bind('<Return>', res)
#Here the button should returning result
resultbutton = Button(win, text="Ok", command=res)
resultbutton.grid(column=2, row=2)
resultlabel = Label(win,text="Result")
resultlabel.grid(column=0, row=2)
#I want result printed here
resultentry = Entry(win, width=30)
resultentry.grid(column=1,row=2)
import tkinter as tk
from tkinter import *
win = tk.Tk()
win.title("Test")
win.configure(background='black')
enternumber = Label(win, text="Enter Number")
enternumber.grid(column=0, row=0)
var1 = IntVar()
txtenternumber = Entry(win, width=20, textvariable=var1)
txtenternumber.grid(column=1, row=0)
enternumber = Label(win, text="Enter Number")
enternumber.grid(column=0, row=1)
var2 = IntVar()
txtenternumber = Entry(win, width=20, textvariable=var2)
txtenternumber.grid(column=1, row=1)
def res():
result = var1.get()*var2.get()
resultentry.insert(0,result) # INSERTS RESULT INTO resultentry
resultentry.bind('<Return>', res)
resultbutton = Button(win, text="Ok", command=res)
resultbutton.grid(column=2, row=2)
resultlabel = Label(win,text="Result")
resultlabel.grid(column=0, row=2)
resultentry = Entry(win, width=30)
resultentry.grid(column=1,row=2)
win.mainloop()
Sorry, forgot to add this. Yes, you just need to use resultentry.insert(0, result)and you should be set. I also like using this as a good resource:
https://effbot.org/tkinterbook/entry.htm
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()
I'm beginner for python and I tried to make a BMI calculator
but i have some problems with the input and output
I want to get input from self.Heighttypeand self.Weighttypeand give a output at self.BMI
And some tips to simply my coding?
from tkinter import *
import tkinter.messagebox
root = Tk()
root.resizable(0,0)
class win1:
def __init__(self, master):
self.master = master
master.title("BMI Calculator")
#
self.he = IntVar()
self.we = IntVar()
self.height = Label(master, text="ENTER Your Height(cm) Here:")
self.Heighttype = Entry(master, textvariable=self.he) #here
self.weight = Label(master,text="ENTER Your Weight(kg) Here:")
self.Weighttype = Entry(master, textvariable=self.we) #and here
#
self.ans = IntVar()
self.BMI = Label(master, textvariable=self.ans) #output here
self.credit = Button(master, text="Credit", command=self.credit_show)
self.result = Button(master, text="Result", command=self.calculation)
root.protocol('WM_DELETE_WINDOW', self.ask_quit)
self.close = Button(master, text="Close", command=self.ask_quit)
self.height.grid(sticky=E, padx=2, pady=4)
self.Heighttype.grid(row=0, column=1, columnspan=2, padx=2)
self.weight.grid(sticky=E, padx=2, pady=4)
self.Weighttype.grid(row=1, column=1, columnspan=2, padx=2)
self.BMI.grid(row=2, column=1, columnspan=2, padx=2)
self.credit.grid(row=3, sticky=W, padx=4 , pady=4)
self.result.grid(row=3, column=1, pady=4, sticky=W+E, padx=4)
self.close.grid(row=3, column=2, pady=4, sticky=W+E, padx=1)
def calculation(self):
# i want to get the user input from top and make calculation
# and make a output self.BMI = Label
def credit_show(self):
tkinter.messagebox.showinfo("Credit","Created by BlackLotus")
def ask_quit(self):
if tkinter.messagebox.askokcancel("Quit", "Do you want to Quit?"):
root.destroy()
apps = win1(root)
root.mainloop()
Someone help me please. Thanks a lot.
Use .get() and .set() on the IntVars to get the parameters and set the result:
def calculation(self):
m = self.we.get()
l = self.he.get()
bmi = # calculate the bmi here
self.ans.set(bmi)
Also, while it seems to work with an IntVar as well, it seems more reasonable to make ans a DoubleVar, i.e.:
self.ans = DoubleVar()
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()