## page was renamed from zhPyCookbookTemplate ##language:zh ''' 文章来自《Python cookbook》. 翻译仅仅是为了个人学习,其它商业版权纠纷与此无关! ''' ::-- KenLai [<<DateTime(2006-03-22T13:28:29Z)>>] <<TableOfContents>> = 描述 = Credit: Luther Blissett == 问题 Problem == 您希望创建一个在顶部有菜单的窗口。 == 解决 Solution == 使用 Tkinter 的Menu widget: {{{ #!python import sys from Tkinter import * root = Tk( ) # Insert a menu bar on the main window menubar = Menu(root) root.config(menu=menubar) # Create a menu button labeled "File" that brings up a menu filemenu = Menu(menubar) menubar.add_cascade(label='File', menu=filemenu) # Create entries in the "File" menu # simulated command functions that we want to invoke from our menus def doPrint( ): print 'doPrint' def doSave( ): print 'doSave' filemenu.add_command(label='Print', command=doPrint) filemenu.add_command(label='Save', command=doSave) filemenu.add_separator( ) filemenu.add_command(label='Quit', command=sys.exit) 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: {{{ #!python 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: {{{ #!python 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.