Python Tkinter Menu bar: Creating Menu items
Write a Python program that creates a basic menu bar with menu items using Tkinter.
Sample Solution:
Python Code:
import tkinter as tk
from tkinter import Menu
# Create the main window
parent = tk.Tk()
parent.title("Spyder (Python 3.6)")
# Create a menu bar
menu_bar = Menu(parent)
parent.config(menu=menu_bar)
# Create a File menu
file_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="File", menu=file_menu)
# Add menu items to the File menu
file_menu.add_command(label="New")
file_menu.add_command(label="Open")
file_menu.add_separator()
file_menu.add_command(label="Exit", command=parent.quit)
# Create an Edit menu
edit_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="Edit", menu=edit_menu)
# Add menu items to the Edit menu
edit_menu.add_command(label="Cut")
edit_menu.add_command(label="Copy")
edit_menu.add_command(label="Paste")
# Create a Help menu
help_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="Help", menu=help_menu)
# Add menu items to the Help menu
help_menu.add_command(label="About Spyder")
# Start the Tkinter event loop
parent.mainloop()
In the exercise above we created a "Tkinter" window with a menu bar with three menus: 'File', 'Edit', and 'Help'. Each menu contains menu items. For example, the File menu has items like "New," "Open," and "Exit." Based on this basic structure, we can expand the menu items and add functionality as needed.
Sample Output:
Flowchart:
Python Code Editor:
Previous: Python Tkinter event handling: Button clicks.
Next: Python Tkinter Messagebox: Display messages.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics