Tkinter and the Menu Widget

Michele Simionato mis6 at pitt.edu
Wed Jun 19 14:15:21 CEST 2002


Hello everybody !

I just started playing with Tkinter. I have a problem with the Menu
Widget. I want to create a menu like that

    File   Help
    -----  -----
    File1  Help1
    File2  Help2

Actually this is a simplified version of what I need since for my application
the number of items N has to be dynamic; here for sake of semplicity I took 
N=2. Notice that I want to store the labels for the various items 
in a dictionary like that:

    menuD={'File':['File1','File2'],'Help':['Help1','Help2']}

This dictionary is created dynamically by another program and can have
much more complicated items.
When I invoke a specific menu a procedure has to be called which
do something on a string of the form "invoked menu=invoked item" (for instance 
"Help=Help1" if I invoked the item Help1 of the menu Help). Suppose for 
sake of simplicity that dosomething(s) simply print the string s, even if
in the real case dosomething() calls an external program which requires
the string s as input. My attempt has been the following code:

    import Tkinter
    def dosomething(s):
        print s
    root=Tkinter.Tk()
    mn=Tkinter.Menu(root) #attach the menu mn to root
    menuD={'File':['File1','File2'],'Help':['Help1','Help2']}
    smn={} #dictionary keys->submenu-objects defined below
    for key in menuD.keys():
        smn[key]=Tkinter.Menu(mn) #define a submenu of mn
        mn.add_cascade(label=key,menu=smn[key]) #attach smn[key] to mn
        for submenu in menuD[key]:
            smn[key].add_command(label=submenu,command=lambda :
                                 dosomething(key+'='+submenu))
    root.config(menu=mn) #display the menu mn
    Tkinter.mainloop()

I used the lambda statement since <command=> requires a callable object
as argument; notice that this code only runs in Python2.2 (in Python2.1
with the statement from __future__ import nested_scopes).

This code correctly creates the menu; however since at the end of the
loop the value of key is 'Help' and the value of submenu is 'Help2',
when I invoke any item of the menu with the mouse, dosomething always 
print the string 'Help=Help2'. Instead, I would like to print the string 
corresponding to the actually called menu ! 
The Tkinter documentation I have is not helpful, I need a way to pass
to dosomething some identification of the called menu. Any suggestion ? 
 
--
Michele Simionato - Dept. of Physics and Astronomy
210 Allen Hall Pittsburgh PA 15260 U.S.A.
Phone: 001-412-624-9041 Fax: 001-412-624-9163
Home-page: http://www.phyast.pitt.edu/~micheles/



More information about the Python-list mailing list