Tkinter Menu
Menu Bar
Most desktop apps have a menu bar at the top of the window, with menus like File and Help:
Example
A menu bar with a File menu:
import tkinter as tk
window = tk.Tk()
window.geometry("300x200")
menubar = tk.Menu(window)
window.config(menu=menubar)
file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(label="New")
file_menu.add_command(label="Open")
file_menu.add_separator()
file_menu.add_command(
label="Exit", command=window.destroy)
menubar.add_cascade(label="File",
menu=file_menu)
window.mainloop()
Result:
After clicking File:
Here is what the code does:
tk.Menu(window)creates the menu bar, andwindow.config(menu=menubar)puts it in the windowtk.Menu(menubar, tearoff=0)creates the File menuadd_command()adds an item, andadd_separator()adds a line between itemsadd_cascade()adds the File menu to the menu bar
Note: tearoff=0 removes a dashed line at the top of the menu. In older programs, the user could click that line to tear the menu off into its own window.
Run a Function From a Menu
Like a button, a menu item has a command. Here, the About item in the Help menu shows a message box:
Example
Show an About box from the Help menu:
import tkinter as tk
from tkinter import messagebox
window = tk.Tk()
window.geometry("300x200")
def about():
messagebox.showinfo(
"About", "My App, version 1.0")
menubar = tk.Menu(window)
window.config(menu=menubar)
help_menu = tk.Menu(menubar, tearoff=0)
help_menu.add_command(label="About",
command=about)
menubar.add_cascade(label="Help",
menu=help_menu)
window.mainloop()
Result:
After clicking Help, then About:
Message boxes are explained in the Tkinter Messagebox chapter.