[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
also open other “cascading” submenus that list more options, pop up dialog windows,
and so on. In tkinter, there are two kinds of menus you can add to your scripts: top-
level window menus and frame-based menus. The former option is better suited to
whole windows, but the latter also works as a nested component.

Top-Level Window Menus


In all recent Python releases (using Tk 8.0 and later), you can associate a horizontal
menu bar with a top-level window object (e.g., a Tk or Toplevel). On Windows and
Unix (X Windows), this menu bar is displayed along the top of the window; on some
Macintosh machines, this menu replaces the one shown at the top of the screen when
the window is selected. In other words, window menus look like you would expect on
whatever underlying platform your script runs upon.
This scheme is based on building trees of Menu w i d g e t o b j e c t s. S i m p l y a s s o c i a t e o n e t o p -
level Menu with the window, add other pull-down Menu objects as cascades of the top-
level Menu, and add entries to each of the pull-down objects. Menus are cross-linked with
the next higher level, by using parent widget arguments and the Menu widget’s
add_cascade method. It works like this:


  1. Create a topmost Menu as the child of the window widget and configure the win-
    dow’s menu attribute to be the new Menu.

  2. For each pull-down object, make a new Menu as the child of the topmost Menu and
    add the child as a cascade of the topmost Menu using add_cascade.

  3. Add menu selections to each pull-down Menu f r o m s t e p 2 , u s i n g t h e command o p t i o n s
    of add_command to register selection callback handlers.

  4. Add a cascading submenu by making a new Menu a s t h e c h i l d o f t h e Menu t h e c a s c a d e
    extends and using add_cascade to link the parent to the child.


The end result is a tree of Menu w i d g e t s w i t h a s s o c i a t e d command c a l l b a c k h a n d l e r s. T h i s
is probably simpler in code than in words, though. Example 9-1 makes a main menu
with two pull downs, File and Edit; the Edit pull down in turn has a nested submenu
of its own.

Example 9-1. PP4E\Gui\Tour\menu_win.py
# Tk8.0 style top-level window menus

from tkinter import * # get widget classes
from tkinter.messagebox import * # get standard dialogs

def notdone():
showerror('Not implemented', 'Not yet available')

def makemenu(win):
top = Menu(win) # win=top-level window
win.config(menu=top) # set its menu option

508 | Chapter 9: A tkinter Tour, Part 2

Do


wnload from Wow! eBook <www.wowebook.com>

Free download pdf