How to Create Menu in Tkinter in Python: Simple Guide
To create a menu in Tkinter, use the
Menu widget and attach it to the root window with root.config(menu=menu_bar). Add menu items using add_command or submenus with add_cascade on the menu bar.Syntax
Here is the basic syntax to create a menu in Tkinter:
menu_bar = Menu(root): Create the main menu bar attached to the root window.file_menu = Menu(menu_bar, tearoff=0): Create a submenu (like File menu).file_menu.add_command(label='Open', command=some_function): Add a clickable menu item.menu_bar.add_cascade(label='File', menu=file_menu): Add the submenu to the menu bar.root.config(menu=menu_bar): Set the menu bar on the main window.
python
menu_bar = Menu(root) file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label='Open', command=some_function) menu_bar.add_cascade(label='File', menu=file_menu) root.config(menu=menu_bar)
Example
This example creates a window with a menu bar containing a File menu. The File menu has an Exit item that closes the window when clicked.
python
import tkinter as tk from tkinter import Menu def exit_app(): root.destroy() root = tk.Tk() root.title('Menu Example') menu_bar = Menu(root) file_menu = Menu(menu_bar, tearoff=0) file_menu.add_command(label='Exit', command=exit_app) menu_bar.add_cascade(label='File', menu=file_menu) root.config(menu=menu_bar) root.mainloop()
Output
A window titled 'Menu Example' opens with a menu bar. Clicking 'File' shows 'Exit'. Clicking 'Exit' closes the window.
Common Pitfalls
Common mistakes when creating menus in Tkinter include:
- Forgetting to attach the menu bar to the root window using
root.config(menu=menu_bar), so the menu does not appear. - Not setting
tearoff=0on submenus, which adds a dashed line that can confuse beginners. - Using incorrect commands or forgetting to define the function called by
command=.
python
import tkinter as tk from tkinter import Menu root = tk.Tk() menu_bar = Menu(root) file_menu = Menu(menu_bar) # Missing tearoff=0 file_menu.add_command(label='Exit') # Missing command menu_bar.add_cascade(label='File', menu=file_menu) # Missing root.config(menu=menu_bar) root.mainloop()
Output
No menu appears because root.config(menu=menu_bar) is missing and Exit does nothing when clicked.
Quick Reference
Summary tips for creating menus in Tkinter:
- Always create a
Menuobject for the menu bar and submenus. - Use
add_commandto add clickable items with a label and command. - Use
add_cascadeto add submenus to the menu bar. - Set
tearoff=0to disable the dashed line on submenus. - Attach the menu bar to the root window with
root.config(menu=menu_bar).
Key Takeaways
Create a Menu object and attach it to the root window with root.config(menu=menu_bar).
Add menu items using add_command with a label and a function to run on click.
Use add_cascade to add submenus to the main menu bar.
Set tearoff=0 on submenus to avoid confusing dashed lines.
Always define functions for menu commands to avoid errors.