17.5. MenusClass Menu implements all kinds of menus: menu bars of top-level windows, submenus, and pop-up menus. To use a Menu instance m as the menu bar for a top-level window w, set w's configuration option menu=m. To use m as a submenu of a Menu instance x, call x.add_cascade with menu=m. To use m as a pop-up menu, call m.post. Besides configuration options covered in "Common Widget Options" on page 409, a Menu instance m supports option postcommand=callable. Tkinter calls callable without arguments each time it is about to display m (because of a call to m.post or because of user actions). Use this option to update a dynamic menu just in time when necessary. By default, a Tkinter menu shows a tear-off entry (a dashed line before other entries), which lets the user get a copy of the menu in a separate Toplevel window. Since such tear-offs are not part of user interface standards on popular platforms, you may want to disable tear-off functionality by using configuration option tearoff=0 for the menu. 17.5.1. Menu-Specific MethodsBesides methods common to all widgets, an instance m of class Menu supplies several menu-specific methods.
17.5.2. Menu EntriesWhen a menu m displays, it shows a vertical (horizontal for a menu bar) list of entries. Each entry can be one of the following kinds:
Other options often used with menu entries are:
17.5.3. Menu ExampleThe following example shows how to add a menu bar with typical File and Edit menus:
import Tkinter
root = Tkinter.Tk( )
bar = Tkinter.Menu( )
def show(menu, entry): print menu, entry
fil = Tkinter.Menu( )
for x in 'New', 'Open', 'Close', 'Save':
fil.add_command(label=x,command=lambda x=x:show('File',x))
bar.add_cascade(label='File',menu=fil)
edi = Tkinter.Menu( )
for x in 'Cut', 'Copy', 'Paste', 'Clear':
edi.add_command(label=x,command=lambda x=x:show('Edit',x))
bar.add_cascade(label='Edit',menu=edi)
root.config(menu=bar)
Tkinter.mainloop( )
In this example, each menu command just outputs information to standard output for demonstration purposes. (Note the x=x idiom to snapshot the value of x at the time we create each lambda.) Otherwise, the current value of x at the time a lambda executes, 'Clear', would show up at each menu selection. A better alternative to the lambda expressions with the x=x idiom is a closure. Instead of def show, use:
def mkshow(menu, entry):
def emit( ): print menu, entry
return emit
and use command=mkshow('File', x) and command=mkshow('Edit', x), respectively, in the calls to the add_command methods of fil and edi. |