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

Guilherme Polo ggpolo at gmail.com
Wed Aug 19 15:32:01 CEST 2009

2009/8/19 thicket <mark_eastwood at ntlworld.com>:
> I have a
> 'partial' solution to what I'm trying to achieve (code snippet below)
> .........
> The issue is that all the 'Actions' after and including Stock/Order history
> will display the same sub-menu (self.mnth_mu).
> The code as it stands enables me to identify which month has been selected
> for a particular 'Action' but not which 'Action' it refers to i.e. works
> fine if self.mnth.mu is used only once.

Well, my real suggestion would be to change this application. Don't
you think it is weird that when you select a month for a specific
action, all the other actions will have the same month selected ? How
can you know which one is active by looking in the menus ? Even if you
changed it to have multiple tcl variables, you still wouldn't know
which exact thing is active.

Nevertheless, I gave it a try and the code is below. It does create a
new menu for each action, but it is just about the same effort of
creating a single one.

import Tkinter

root = Tkinter.Tk()

def test(action):
    def cb():
        print month_var.get(), action
    return cb

def create_month_menu(action):
    month_menu = Tkinter.Menu(action_menu, tearoff=False)
    for month in ('Jan', 'Feb', 'Mar'):
        month_menu.add_radiobutton(label=month, variable=month_var,
    return month_menu

menu = Tkinter.Menu(tearoff=False)
action_menu = Tkinter.Menu(menu, tearoff=False)
month_var = Tkinter.StringVar()

for action in ('A1', 'A2'):
    action_menu.add_cascade(label=action, menu=create_month_menu(action))

menu.add_cascade(label='Actions', menu=action_menu)
root['menu'] = menu


-- Guilherme H. Polo Goncalves

More information about the Tkinter-discuss mailing list