1

The code,

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()

I have 2 comboboxes, one for current age, and one for target age. I want target age to contain only values that are above current age. Therefore, I think I need to register on change callback somehow. I searched the google, but it didn't help.

yasar
  • 13,158
  • 28
  • 95
  • 160

2 Answers2

2

Here you have the function that modifies the target menuoptions and the event that triggers it:

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)

This has taken in part from here, here and here.

Community
  • 1
  • 1
joaquin
  • 82,968
  • 29
  • 138
  • 152
  • Thanks. But after setting current age, target age gets fixed that I can't change it's value any more. – yasar Jan 01 '13 at 13:57
1

It should be clear that OptionMenu is a poor choice for the situation, no one likes to select an option over a menu of 95 entries. Anyway, you don't need to depend on Tcl variable tracing to do the update, just remember about the command argument that OptionMenu accepts. Using that, your problem is solved as in:

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()
mmgp
  • 18,901
  • 3
  • 53
  • 80