本博客是翻译文章。
翻译文章来源于http://effbot.org/tkinterbook/menu.htm。
下面一边看代码一遍学习怎么创建和使用Menu
理解menu的使用方法主要在于下面几个方法:
#这个方法是给主菜单加上一个子菜单。【当然你也可以给子菜单再加上一个子菜单】
.add_command(label=string, command=callback)
#这个方法是加上一个分割线
.add_separator()
#这个方法是加上一个主菜单
.add_cascade(label=string, menu=menu istance)
总结性:
(1)在一个窗口加上一个菜单首先得要在root窗口控件中创建一个根菜单。
menubar = Menu(root)
(2)再在根菜单里面加上子菜单。
例如本示例加了三个菜单。
menubar.add_cascade(label="File", menu=filemenu)
menubar.add_cascade(label="Edit", menu=editmenu)
menubar.add_cascade(label="Help", menu=helpmenu)
(3)子菜单里面也可以再创造菜单,例如File的菜单里面创造了几个下拉的菜单同时还在菜单Save和Exit之间加上了分割线。
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=hello)
filemenu.add_command(label="Save", command=hello)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
完整代码示例:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : SundayCoder-俊勇
# @File : Menu1.py
from Tkinter import *
root = Tk()
def hello():
print "hello!"
menubar = Menu(root)
# create a pulldown menu, and add it to the menu bar
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=hello)
filemenu.add_command(label="Save", command=hello)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
# create more pulldown menus
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Cut", command=hello)
editmenu.add_command(label="Copy", command=hello)
editmenu.add_command(label="Paste", command=hello)
menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="About", command=hello)
menubar.add_cascade(label="Help", menu=helpmenu)
# display the menu
root.config(menu=menubar)
root.mainloop()