一、參數說明
| 語法 | 作用 |
|---|---|
| MenuBar = tk.Menu(window) | 創建一個菜單欄 |
| fileBar = tk.Menu(MenuBar, tearoff=0) | 創建一個菜單項,不分窗。 |
| MenuBar.add_cascade(label="File", menu=fileBar) | 在菜單欄添加File菜單 |
| fileBar.add_command(label="open") | 在菜單項中加入子菜單 |
| fileBar.add_separator() | 在菜單項中加入一條分割線 |
| window.config(menu =MenuBar) | 放置菜單欄到主窗口 |
| fileBar.delete(0) | 刪除第一個位置菜單項 |
| MenuBar.add_checkbutton | 添加確認按鈕 |
二、代碼示例
import tkinter as tk
window = tk.Tk()
# 設置窗口大小
winWidth = 600
winHeight = 400
# 獲取屏幕分辨率
screenWidth = window.winfo_screenwidth()
screenHeight = window.winfo_screenheight()
x = int((screenWidth - winWidth) / 2)
y = int((screenHeight - winHeight) / 2)
# 設置主窗口標題
window.title("Menu菜單參數說明")
# 設置窗口初始位置在屏幕居中
window.geometry("%sx%s+%s+%s" % (winWidth, winHeight, x, y))
# 設置窗口圖標
window.iconbitmap("./image/icon.ico")
# 設置窗口寬高固定
window.resizable(0, 0)
"""menu參數.
Valid resource names: activebackground, activeborderwidth,
activeforeground, background, bd, bg, borderwidth, cursor,
disabledforeground, fg, font, foreground, postcommand, relief,
selectcolor, takefocus, tearoff, tearoffcommand, title, type."""
# 創建菜單欄
MenuBar = tk.Menu(window)
# 將菜單欄放到主窗口
window.config(menu =MenuBar)
# 創建文件菜單,不顯示分窗
fileBar = tk.Menu(MenuBar, tearoff=0)
# 添加文件菜單項
fileBar.add_command(label="open")
fileBar.add_command(label="save")
fileBar.add_command(label="save as")
# 創建分割線
fileBar.add_separator()
fileBar.add_command(label="exit", command=window.destroy)
# 將文件菜單添加到菜單欄
MenuBar.add_cascade(label="File", menu=fileBar)
def deleteMenu():
# 刪除第一個位置菜單項
fileBar.delete(0)
tk.Button(window, text="刪除", command=deleteMenu).pack()
window.mainloop()
三、效果圖

