1

编码,

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 个组合框,一个用于当前年龄,一个用于目标年龄。我希望目标年龄仅包含高于当前年龄的值。因此,我认为我需要以某种方式注册更改回调。我搜索了谷歌,但它没有帮助。

4

2 回答 2

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)

这部分来自这里这里这里

于 2013-01-01T13:49:20.227 回答
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()
于 2013-01-02T19:57:47.173 回答