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

(yzsuai) #1

file = Menu(top)
file.add_command(label='New...', command=notdone, underline=0)
file.add_command(label='Open...', command=notdone, underline=0)
file.add_command(label='Quit', command=win.quit, underline=0)
top.add_cascade(label='File', menu=file, underline=0)


edit = Menu(top, tearoff=False)
edit.add_command(label='Cut', command=notdone, underline=0)
edit.add_command(label='Paste', command=notdone, underline=0)
edit.add_separator()
top.add_cascade(label='Edit', menu=edit, underline=0)


submenu = Menu(edit, tearoff=True)
submenu.add_command(label='Spam', command=win.quit, underline=0)
submenu.add_command(label='Eggs', command=notdone, underline=0)
edit.add_cascade(label='Stuff', menu=submenu, underline=0)


if name == 'main':
root = Tk() # or Toplevel()
root.title('menu_win') # set window-mgr info
makemenu(root) # associate a menu bar
msg = Label(root, text='Window menu basics') # add something below
msg.pack(expand=YES, fill=BOTH)
msg.config(relief=SUNKEN, width=40, height=7, bg='beige')
root.mainloop()


A lot of code in this file is devoted to setting callbacks and such, so it might help to
isolate the bits involved with the menu tree-building process. For the File menu, it’s
done like this:


top = Menu(win) # attach Menu to window
win.config(menu=top) # cross-link window to menu
file = Menu(top) # attach a Menu to top Menu
top.add_cascade(label='File', menu=file) # cross-link parent to child

Apart from building up the menu object tree, this script also demonstrates some of the
most common menu configuration options:


Separator lines
The script makes a separator in the Edit menu with add_separator; it’s just a line
used to set off groups of related entries.


Tear-offs
The script also disables menu tear-offs in the Edit pull down by passing a
tearoff=False widget option to Menu. Tear-offs are dashed lines that appear by
default at the top of tkinter menus and create a new window containing the menu’s
contents when clicked. They can be a convenient shortcut device (you can click
items in the tear-off window right away, without having to navigate through menu
trees), but they are not widely used on all platforms.


Keyboard shortcuts
The script uses the underline option to make a unique letter in a menu entry a
keyboard shortcut. It gives the offset of the shortcut letter in the entry’s label string.


Menus | 509
Free download pdf