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

(yzsuai) #1

Label(win, bg='black', height=5, width=25).pack(expand=YES, fill=BOTH)
Button(root, text="Bye", command=root.quit).pack()
root.mainloop()


Frame- and Menubutton-Based Menus


Although these are less commonly used for top-level windows, it’s also possible to
create a menu bar as a horizontal Frame. Before I show you how, though, let me explain
why you should care. Because this frame-based scheme doesn’t depend on top-level
window protocols, it can also be used to add menus as nested components of larger
displays. In other words, it’s not just for top-level windows. For example, Chap-
ter 11’s PyEdit text editor can be used both as a program and as an attachable compo-
nent. We’ll use window menus to implement PyEdit selections when PyEdit is run as
a standalone program, but we’ll use frame-based menus when PyEdit is embedded in
the PyMailGUI and PyView displays. Both schemes are worth knowing.


Frame-based menus require a few more lines of code, but they aren’t much more com-
plex than window menus. To make one, simply pack Menubutton widgets within a
Frame container, associate Menu widgets with the Menubuttons, and associate the Frame
with the top of a container window. Example 9-3 creates the same menu as Exam-
ple 9-2, but using the frame-based approach.


Example 9-3. PP4E\Gui\Tour\menu_frm.py


Frame-based menus: for top-levels and components


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


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


def makemenu(parent):
menubar = Frame(parent) # relief=RAISED, bd=2...
menubar.pack(side=TOP, fill=X)


fbutton = Menubutton(menubar, text='File', underline=0)
fbutton.pack(side=LEFT)
file = Menu(fbutton)
file.add_command(label='New...', command=notdone, underline=0)
file.add_command(label='Open...', command=notdone, underline=0)
file.add_command(label='Quit', command=parent.quit, underline=0)
fbutton.config(menu=file)


ebutton = Menubutton(menubar, text='Edit', underline=0)
ebutton.pack(side=LEFT)
edit = Menu(ebutton, tearoff=False)
edit.add_command(label='Cut', command=notdone, underline=0)
edit.add_command(label='Paste', command=notdone, underline=0)
edit.add_separator()
ebutton.config(menu=edit)


512 | Chapter 9: A tkinter Tour, Part 2

Free download pdf