[Tkinter-discuss] How do I identify which menu item has bee selected?

Guilherme Polo ggpolo at gmail.com
Wed Aug 19 13:41:22 CEST 2009

2009/8/18 thicket <mark_eastwood at ntlworld.com>:
> Hi - am using python 2.6 and Tkinter 8.5.
> I would like to know how to identify which 'menu item' has been selected
> from a cascaded menu.
> The cascaded menu menu items are variable and created on the fly. The idea
> is to use a common callback for all menu items, the callback function then
> determines which selection was made and runs the appropriate function.
> I have tried binding an event to the selection and then trying to get some
> sort of info from the event object (event.widget()) but this appears to
> return info about the menu class instance and not about it's menu items.

I will try something here, but since you didn't post what you tried it
may not be what you want. I always see my own code indented on email,
but if that is not the case for everyone then it is better to move it
to some paste bin.
Anyway, below is an attempt to do what you want but there is a problem
with it. If you can't guarantee that new entries are added to the end,
then the code needs to be adapted.

import Tkinter

root = Tkinter.Tk()

menu = Tkinter.Menu(root, tearoff=False)

def test(parent, index):
    def cb():
        print parent.entrycget(index, 'label')
    return cb

def build_menu(descr, parent):
    for item in descr:
        if isinstance(item, list):
            menu = Tkinter.Menu(root, tearoff=False)
            parent.add_cascade(label=item[0], menu=menu)
            build_menu(item[1], menu)
            indx = parent.index('last')
            if indx is None:
                indx = 0
                indx += 1
            parent.insert_command(index=indx, label=item,
                    command=test(parent, indx))

menudescr = [['File', [['Recent file list', ['a', 'b', 'c']]]]]
build_menu(menudescr, menu)

root['menu'] = menu

-- Guilherme H. Polo Goncalves

More information about the Tkinter-discuss mailing list