How to Create a Menu Bar in Tkinter

Step 1: Import Tkinter

import tkinter as tk
from tkinter import messagebox

Step 2: Create the Main Window

root = tk.Tk()
root.title("Multiple Menu Example")
root.geometry("400x300")

Step 3: Create the Menu Bar

menubar = tk.Menu(root)

Step 4: Create Main Menus (e.g., File, Edit, Help)

# File Menu
file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(label="New", command=lambda: messagebox.showinfo("New", "Create a new file"))
file_menu.add_command(label="Open", command=lambda: messagebox.showinfo("Open", "Open a file"))
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)

Step 5: Add Another Menu (Edit, Help, etc.)

# Edit Menu
edit_menu = tk.Menu(menubar, tearoff=0)
edit_menu.add_command(label="Undo", command=lambda: messagebox.showinfo("Undo", "Undo action"))
edit_menu.add_command(label="Redo", command=lambda: messagebox.showinfo("Redo", "Redo action"))

# Help Menu
help_menu = tk.Menu(menubar, tearoff=0)
help_menu.add_command(label="About", command=lambda: messagebox.showinfo("About", "This is a Tkinter menu demo"))

Step 6: Add Menus to the Menu Bar

menubar.add_cascade(label="File", menu=file_menu)
menubar.add_cascade(label="Edit", menu=edit_menu)
menubar.add_cascade(label="Help", menu=help_menu)

Step 7: Configure the Menu Bar in the Main Window

root.config(menu=menubar)

Step 8: Run the App

root.mainloop()

Step 9: Complete Code

import tkinter as tk
from tkinter import messagebox

root = tk.Tk()
root.title("Multiple Menu Example")
root.geometry("400x300")

menubar = tk.Menu(root)

# File Menu
file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(label="New", command=lambda: messagebox.showinfo("New", "Create a new file"))
file_menu.add_command(label="Open", command=lambda: messagebox.showinfo("Open", "Open a file"))
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=file_menu)

# Edit Menu
edit_menu = tk.Menu(menubar, tearoff=0)
edit_menu.add_command(label="Undo", command=lambda: messagebox.showinfo("Undo", "Undo action"))
edit_menu.add_command(label="Redo", command=lambda: messagebox.showinfo("Redo", "Redo action"))
menubar.add_cascade(label="Edit", menu=edit_menu)

# Help Menu
help_menu = tk.Menu(menubar, tearoff=0)
help_menu.add_command(label="About", command=lambda: messagebox.showinfo("About", "This is a Tkinter menu demo"))
menubar.add_cascade(label="Help", menu=help_menu)

root.config(menu=menubar)
root.mainloop()

Leave a Reply

Your email address will not be published. Required fields are marked *