Tkinter菜單Menu的使用示例

本博客是翻譯文章。
翻譯文章來源於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()

這裏寫圖片描述
這裏寫圖片描述

發佈了47 篇原創文章 · 獲贊 26 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章