Menu類控件用來實現頂層/下拉/彈出菜單。
Patterns
Toplevel menus被用來顯示在標題欄/root窗口或者其他頂層窗口上。創建一個頂層菜單,創建Menu類的實例,然後使用add方法添加命令或者其他菜單內容。
root = Tk()
def hello():
print "hello!"
# create a toplevel menu
menubar = Menu(root)
menubar.add_command(label="Hello!", command=hello)
menubar.add_command(label="Quit!", command=root.quit)
# display the menu
root.config(menu=menubar)
root.mainloop()
運行程序,如下圖所示:
下拉菜單或者其他子菜單可以通過相同的方式創建。一個主要的區別就是,他們是依附在主菜單上的(通過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)
最後我們通過同樣的方式創建一個彈出式菜單,但是通過post方法顯示顯示。
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)
我們也可以在任何時候使用postcommand 回調函數去創建或更新顯示的菜單。
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。
第一次點擊:
第二次點擊: