文章来自《Python cookbook》. 翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!
::-- hellopython [2005-03-01 13:11:51]
You want to create a window that has a menu bar at the top. 你想在一个窗口上建个目录条
You want to create a window that has a menu bar at the top.
1 import sys 2 from Tkinter import * 3 4 root = Tk( ) 5 6 # Insert a menu bar on the main window 7 menubar = Menu(root) 8 root.config(menu=menubar) 9 10 # Create a menu button labeled "File" that brings up a menu 11 filemenu = Menu(menubar) 12 menubar.add_cascade(label='File', menu=filemenu) 13 14 # Create entries in the "File" menu 15 # simulated command functions that we want to invoke from our menus 16 def doPrint( ): print 'doPrint' 17 def doSave( ): print 'doSave' 18 filemenu.add_command(label='Print', command=doPrint) 19 filemenu.add_command(label='Save', command=doSave) 20 filemenu.add_separator( ) 21 filemenu.add_command(label='Quit', command=sys.exit) 22 23 root.mainloop( )
Menus in Tkinter applications are handled entirely by the Menu widget. As shown in the recipe, you use Menu both for the top-level menu bar (which you add to a top-level window as its menu configuration setting) and for cascading menus (which you add to the menu bar, or to other menus, with the add_cascade method).
A menu can have several kinds of entries. A cascade entry pops up a submenu when the user selects it, and is added with add_cascade. A command entry calls a function when the user selects it, and is added with add_command. A separator visually separates other entries, and is added with add_separator.
A checkbutton entry is added with add_checkbutton and has an associated Tkinter IntVar, with an on value and an off value. If the associated variable has the on value, the entry displays a check besides its value; if it has the off value, it doesn't. When the user selects the entry, this toggles the state of the variable:
vdebug = IntVar( ) filemenu.add_checkbutton(label='Debug', var=vdebug) You can access the value of vdebug by calling vdebug.get and set it to any integer value n by calling vdebug.set(n). A checkbutton entry can also optionally have a command to call a function when the user selects it.
A group of radiobutton entries is associated with a single IntVar instance. Only one radiobutton associated with that variable can be on at any time. Selecting a radiobutton gives the variable the value associated with it:
vlevel = IntVar( ) filemenu.add_radiobutton(label='Level 1', var=vlevel, value=1) filemenu.add_radiobutton(label='Level 2', var=vlevel, value=2) filemenu.add_radiobutton(label='Level 3', var=vlevel, value=3) A radiobutton entry can also optionally have a command to call a function when the user selects it.
参考 See Also
Information about Tkinter can be obtained from a variety of sources, such as Pythonware's An Introduction to Tkinter, by Fredrik Lundh (http://www.pythonware.com/library), New Mexico Tech's Tkinter reference (http://www.nmt.edu/tcc/help/lang/python/docs.html), and various books.