Patterns
Toplevel menus被用来显示在标题栏/root窗口或者其他顶层窗口上。创建一个顶层菜单,创建Menu类的实例,然后使用add方法添加命令或者其他菜单内容。
下拉菜单或者其他子菜单可以通过相同的方式创建。一个主要的区别就是,他们是依附在主菜单上的(通过add_cascade方法),而不是在顶层窗口上。
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 = Tk() def hello(): print "hello!" # create a popup menu menu = Menu(root, tearoff=0) menu.add_command(label="Undo", command=hello) menu.add_command(label="Redo", command=hello) # create a canvas frame = Frame(root, width=512, height=512) frame.pack() def popup(event): menu.post(event.x_root, event.y_root) # attach popup to canvas frame.bind("<Button-3>", popup)
counter = 0 def update(): global counter counter = counter + 1 menu.entryconfig(0, label=str(counter)) root = Tk() menubar = Menu(root) menu = Menu(menubar, tearoff=0, postcommand=update) menu.add_command(label=str(counter)) menu.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="Test", menu=menu) root.config(menu=menubar)
运行此程序,点击子菜单里第一个选项,就会调用update方法,从而重新配置自己,下一次再次点击时,选项显示的字符会自动加1。
第一次点击:
第二次点击: