這是一個 Tkinter Menu 的完整範例,展示如何建立選單,包括 主選單、下拉選單、子選單、分隔線、快捷鍵,以及 "關於" 對話框。
完整 Tkinter 選單範例
import tkinter as tk
from tkinter import messagebox
# 創建主視窗
root = tk.Tk()
root.title("Tkinter Menu 範例")
root.geometry("400x300")
# 創建主選單
menu_bar = tk.Menu(root)
# **檔案 (File) 選單**
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="開啟 (Ctrl+O)", command=lambda: messagebox.showinfo("開啟", "開啟檔案"))
file_menu.add_command(label="儲存 (Ctrl+S)", command=lambda: messagebox.showinfo("儲存", "儲存檔案"))
file_menu.add_separator()
file_menu.add_command(label="離開 (Ctrl+Q)", command=root.quit) # 離開應用程式
menu_bar.add_cascade(label="檔案 (File)", menu=file_menu)
# **編輯 (Edit) 選單**
edit_menu = tk.Menu(menu_bar, tearoff=0)
edit_menu.add_command(label="剪下 (Ctrl+X)", command=lambda: messagebox.showinfo("剪下", "剪下文字"))
edit_menu.add_command(label="複製 (Ctrl+C)", command=lambda: messagebox.showinfo("複製", "複製文字"))
edit_menu.add_command(label="貼上 (Ctrl+V)", command=lambda: messagebox.showinfo("貼上", "貼上文字"))
menu_bar.add_cascade(label="編輯 (Edit)", menu=edit_menu)
# **說明 (Help) 選單**
help_menu = tk.Menu(menu_bar, tearoff=0)
help_menu.add_command(label="關於 (About)", command=lambda: messagebox.showinfo("關於", "這是一個 Tkinter 範例"))
menu_bar.add_cascade(label="說明 (Help)", menu=help_menu)
# **設定主選單**
root.config(menu=menu_bar)
# **鍵盤快捷鍵 (熱鍵)**
root.bind("<Control-o>", lambda event: messagebox.showinfo("開啟", "快捷鍵 - 開啟檔案"))
root.bind("<Control-s>", lambda event: messagebox.showinfo("儲存", "快捷鍵 - 儲存檔案"))
root.bind("<Control-q>", lambda event: root.quit)
# 執行主視窗
root.mainloop()
功能解釋
1️⃣ 主選單 menu_bar
menu_bar = tk.Menu(root):創建主選單。root.config(menu=menu_bar):將選單設定到視窗。
2️⃣ File (檔案) 選單
file_menu = tk.Menu(menu_bar, tearoff=0):創建子選單,tearoff=0禁用分離選單。add_command(label="開啟", command=...):添加功能選項。add_separator():添加分隔線。file_menu.add_command(label="離開", command=root.quit):點擊後關閉應用程式。
3️⃣ Edit (編輯) 選單
- 包含
剪下、複製、貼上功能。
4️⃣ Help (說明) 選單
- 包含
"關於",點擊後顯示messagebox.showinfo()。
5️⃣ 鍵盤快捷鍵
root.bind("<Control-o>", lambda event: ...)綁定Ctrl+O快捷鍵。root.bind("<Control-s>", lambda event: ...)綁定Ctrl+S快捷鍵。root.bind("<Control-q>", lambda event: root.quit)綁定Ctrl+Q快速退出程式。
額外擴展
你可以加入更多 子選單,例如:
submenu = tk.Menu(file_menu, tearoff=0)
submenu.add_command(label="最近開啟的檔案 1")
submenu.add_command(label="最近開啟的檔案 2")
file_menu.add_cascade(label="最近開啟", menu=submenu)
這樣 File 選單中會有一個 "最近開啟" 的 子選單。
沒有留言:
張貼留言