代码,
from Tkinter import *
master = Tk()
Label(master, text="Current Age: ").grid(row=0, column=0)
current = StringVar(master)
current.set("0")
coption = OptionMenu(master, current, *[str(i) for i in range(95)])
coption.grid(row=0,column=1)
Label(master, text="Target Age: ").grid(row=1, column=0)
target = StringVar(master)
target.set("0") # default deger
toption = OptionMenu(master, target, *[str(i) for i in range(95)])
toption.grid(row=1,column=1)
mainloop()
我有2个组合框,一个用于当前年龄,一个用于目标年龄。我希望目标年龄仅包含高于当前年龄的值。因此,我认为我需要以某种方式注册更改回调。我搜索了谷歌,但它没有帮助。
答案 0 :(得分:2)
这里有一个修改目标菜单选项和触发它的事件的函数:
def changed(*args):
start = current.get()
print(start)
menu = toption["menu"]
menu.delete(0, END)
for age in range(int(start), 95):
menu.add_command(label=age,
command=lambda v=target, l=age: v.set(l))
target.set(start)
current.trace('w', changed)
答案 1 :(得分:1)
应该很清楚OptionMenu
对于这种情况来说是一个糟糕的选择,没有人喜欢在95个条目的菜单上选择一个选项。无论如何,您不需要依赖Tcl变量跟踪来进行更新,只需记住command
接受的OptionMenu
参数。使用它,您的问题解决方案如下:
import Tkinter
AGELIMIT = 95
AGEOPT = [str(i) for i in range(AGELIMIT)]
def update_agelist(currage):
# Rewrite the Menubutton associated with the Optionmenu.
menu = toption['menu']
menu.delete(0, 'end')
for age in range(int(currage), AGELIMIT):
menu.add_command(label=age, command=Tkinter._setit(target, age))
target.set(currage)
master = Tkinter.Tk()
Tkinter.Label(text=u"Current Age: ").grid(row=0, column=0)
current = Tkinter.StringVar(value='0')
coption = Tkinter.OptionMenu(master, current, *AGEOPT, command=update_agelist)
coption.grid(row=0,column=1)
Tkinter.Label(text=u"Target Age: ").grid(row=1, column=0)
target = Tkinter.StringVar(value='0')
toption = Tkinter.OptionMenu(master, target, *AGEOPT)
toption.grid(row=1, column=1)
master.mainloop()