现在的位置: 首页 > 综合 > 正文

Python Tkinter Menu使用教程

2014年07月08日 ⁄ 综合 ⁄ 共 1974字 ⁄ 字号 评论关闭

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。

第一次点击:


第二次点击:

抱歉!评论已关闭.