please to generate an python gui program with main menu and sub menu using tkinter
- User
please to generate an python gui program with main menu and sub menu using tkinter
- Assistant
Sure! Let's create a simple Python GUI application using Tkinter with a main menu and a sub-menu. In this example, we will create a window with a main menu that includes two items: 'File' and 'Edit'. Under 'File', there will be two sub-menu items 'New' and 'Exit'. And under 'Edit', we will add 'Cut' and 'Copy' sub-menu items. Each menu item will perform a simple action when selected.
import tkinter as tk from tkinter import messagebox def new_file(): messagebox.showinfo("New File", "You have selected New File.") def exit_app(): window.quit() def cut_text(): messagebox.showinfo("Cut", "You have selected Cut.") def copy_text(): messagebox.showinfo("Copy", "You have selected Copy.") window = tk.Tk() window.title("Menu Example") # Creating a menu bar menu_bar = tk.Menu(window) # Creating the 'File' menu file_menu = tk.Menu(menu_bar, tearoff=0) file_menu.add_command(label="New", command=new_file) file_menu.add_separator() file_menu.add_command(label="Exit", command=exit_app) menu_bar.add_cascade(label="File", menu=file_menu) # Creating the 'Edit' menu edit_menu = tk.Menu(menu_bar, tearoff=0) edit_menu.add_command(label="Cut", command=cut_text) edit_menu.add_command(label="Copy", command=copy_text) menu_bar.add_cascade(label="Edit", menu=edit_menu) # Display the menu window.config(menu=menu_bar) window.mainloop()Explanation
-
Tkinter Import and Functions: We start by importing the
tkintermodule. We also define functions (new_file,exit_app,cut_text, andcopy_text) that will be called when the respective menu items are selected. They trigger simple message boxes usingmessagebox.showinfo()to demonstrate functionality. -
Window Setup: We create a Tkinter window (
window) and set its title to "Menu Example". -
Menu Bar: A menu bar (
menu_bar) is created by instantiatingtk.Menu. It will contain all of our menu items. -
File Menu: We create a
file_menu, specifyingmenu_baras its parent andtearoff=0to prevent it from being separated from the window. We add commands like 'New' and 'Exit' usingfile_menu.add_command(). A separator is added for visual distinction. The menu is added to themenu_barusingadd_cascade(). -
Edit Menu: Similarly, an
edit_menuis created with 'Cut' and 'Copy' commands. This menu is also added to themenu_bar. -
Configuring the Window: We configure the window to use our
menu_baras its menu. -
Mainloop: We call
window.mainloop()to keep the window displaying.
Run this code in your Python environment. You will get a simple GUI application with a main menu, sub-menus, and dialog messages when the menu items are selected.
-