我想知道如何创建一个动态按钮来调用OptionMenu Widget中选择的功能。
在倒数第二行[-2]中,我将“command = daily_return”替换为“command = var”,但它不起作用。
有什么建议吗? 最好
工作代码
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( )
答案 0 :(得分:1)
有时最简单的解决方案就是足够好:
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)