[Tutor] Tkinter event for changing OptionMenu items

Michael Lange klappnase at freenet.de
Sat Jul 23 23:20:02 CEST 2005

On Thu, 21 Jul 2005 14:16:05 -0400
Bernard Lebel <3dbernard at gmail.com> wrote:

> Hi Michael,
> Let say I have a MenuOption, that consists of 3 items. This MenuOption
> sits on top of the Tkinter window.
> In the lower part, I have a bunch of widgets (text fields). When the
> choose a different item from the MenuOption, it would call a function
> that clears the lower part and repopulates it with new fields. My
> problem is binding this callback to the event of choosing an item.

In this case I would try the StringVar()'s trace method, which you can use to
track changes of its value; a simple example:

>>> from Tkinter import *
>>> root = Tk()
>>> s = StringVar()
>>> s.set('a')
>>> om = OptionMenu(root, s, 'a', 'b', 'c', 'd')
>>> om.pack()
>>> def changed(*args):
...     print s.get()
>>> s.trace('w', changed)

In the example changed() is called each time you select an item in the menu and with
s.get() you can query the current selection and update the window according to the current value.

I hope this helps


More information about the Tutor mailing list