Because they are not tied to the enclosing window, frame-based menus can also be used
as part of another attachable component’s widget package. For example, the menu-
embedding behavior in Example 9-5 works even if the menu’s parent is another
Frame container and not the top-level window; this script is similar to the prior, but
creates three fully functional menu bars attached to frames nested in a window.
Example 9-5. PP4E\Gui\Tour\menu_frm-multi2.py
from menu_frm import makemenu # can't use menu_win here--root=Frame
from tkinter import *
root = Tk()
for i in range(3): # three menus nested in the containers
frm = Frame()
mnu = makemenu(frm)
mnu.config(bd=2, relief=RAISED)
frm.pack(expand=YES, fill=BOTH)
Label(frm, bg='black', height=5, width=25).pack(expand=YES, fill=BOTH)
Button(root, text="Bye", command=root.quit).pack()
root.mainloop()
Using Menubuttons and Optionmenus
In fact, menus based on Menubutton are even more general than Example 9-3 implies—
they can actually show up anywhere on a display that normal buttons can, not just
within a menu bar Frame. Example 9-6 makes a Menubutton pull-down list that simply
shows up by itself, attached to the root window; Figure 9-8 shows the GUI it produces.
Example 9-6. PP4E\Gui\Tour\mbutton.py
from tkinter import *
root = Tk()
mbutton = Menubutton(root, text='Food') # the pull-down stands alone
picks = Menu(mbutton)
mbutton.config(menu=picks)
picks.add_command(label='spam', command=root.quit)
picks.add_command(label='eggs', command=root.quit)
picks.add_command(label='bacon', command=root.quit)
mbutton.pack()
mbutton.config(bg='white', bd=4, relief=RAISED)
root.mainloop()
The related tkinter Optionmenu widget displays an item selected from a pull-down menu.
It’s roughly like a Menubutton plus a display label, and it displays a menu of choices
when clicked, but you must link tkinter variables (described in Chapter 8) to fetch the
choice after the fact instead of registering callbacks, and menu entries are passed as
arguments in the widget constructor call after the variable.
Example 9-7 illustrates typical Optionmenu usage and builds the interface captured in
Figure 9-9. Clicking on either of the first two buttons opens a pull-down menu of
Menus | 515