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

(yzsuai) #1

In addition to simple selections and cascades, menus can also contain disabled entries,
check button and radio button selections, and bitmap and photo images. The next
section demonstrates how some of these special menu entries are programmed.


Windows with Both Menus and Toolbars


Besides showing a menu at the top, it is common for windows to display a row of
buttons at the bottom. This bottom button row is usually called a toolbar, and it often
contains shortcuts to items also available in the menus at the top. It’s easy to add a
toolbar to windows in tkinter—simply pack buttons (and other kinds of widgets) into
a frame, pack the frame on the bottom of the window, and set it to expand horizontally
only. This is really just hierarchical GUI layout at work again, but make sure to pack
toolbars (and frame-based menu bars) early so that other widgets in the middle of the
display are clipped first when the window shrinks; you usually want your tool and menu
bars to outlive other widgets.


Example 9-8 shows one way to go about adding a toolbar to a window. It also dem-
onstrates how to add photo images in menu entries (set the image attribute to a Photo
Image object) and how to disable entries and give them a grayed-out appearance (call
the menu entryconfig method with the index of the item to disable, starting from 1).
Notice that PhotoImage objects are saved as a list; remember, unlike other widgets, these
go away if you don’t hold on to them (see Chapter 8 if you need a refresher).


Example 9-8. PP4E\Gui\Tour\menuDemo.py


#!/usr/local/bin/python
"""
Tk8.0 style main window menus
menu/tool bars packed before middle, fill=X (pack first=clip last);
adds photo menu entries; see also: add_checkbutton, add_radiobutton
"""


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


class NewMenuDemo(Frame): # an extended frame
def init(self, parent=None): # attach to top-level?
Frame.init(self, parent) # do superclass init
self.pack(expand=YES, fill=BOTH)
self.createWidgets() # attach frames/widgets
self.master.title("Toolbars and Menus") # set window-manager info
self.master.iconname("tkpython") # label when iconified


def createWidgets(self):
self.makeMenuBar()
self.makeToolBar()
L = Label(self, text='Menu and Toolbar Demo')
L.config(relief=SUNKEN, width=40, height=10, bg='white')
L.pack(expand=YES, fill=BOTH)


Menus | 517
Free download pdf