w3resource

Python Tkinter Menu bar: Creating Menu items

Python tkinter Basic: Exercise-8 with Solution

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:

Tkinter: Python Tkinter event handling: Button clicks. Part-1
Tkinter: Python Tkinter event handling: Button clicks. Part-2

Flowchart:

Flowchart: Python Tkinter event handling: Button clicks.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/tkinter/python-tkinter-basic-exercise-8.php