文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

::-- KenLai [2006-03-22 13:28:29]

描述

Credit: Luther Blissett

问题 Problem

您希望创建一个在顶部有菜单的窗口。

解决 Solution

使用 Tkinter 的Menu widget:

   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(  )

讨论 Discussion

Tkinter 程序中的菜单完全由 Menu widget 来控制。就像在处方中的例子,Menu 同时用来创建顶层菜单(使用 menu 作为配置设定给窗口添加的顶层菜单)和层叠菜单(由 add_cascade 方法添加到菜单栏或者其他菜单上)。

菜单有很多入口。 当用户选中时,层叠菜单的入口弹出由 add_cascade 创建的子菜单。 命令入口调用由 add_command 指定的函数。 或者是由 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:

   1 vdebug = IntVar(  )
   2 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:

   1 vlevel = IntVar(  )
   2 filemenu.add_radiobutton(label='Level 1', var=vlevel, value=1)
   3 filemenu.add_radiobutton(label='Level 2', var=vlevel, value=2)
   4 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.