Intro
In this blog, I am going to create a Menu Bar in a Python GUI application. It will display the file and help menus on the application screen. When a user clicks "Exit item" in file menu, the Python application will close.
Software requirement
Python 3.5 and IDLE (Python 3.5)
Programming code
-
- import tkinter as tk
- from tkinter import ttk
- from tkinter import Menu
- win = tk.Tk()
- win.title("Python GUI App")
-
- def _quit():
- win.quit()
- win.destroy()
- exit()
-
- menuBar=Menu(win)
- win.config(menu=menuBar)
-
- fileMenu= Menu(menuBar, tearoff=0)
- fileMenu.add_command(label="New")
- fileMenu.add_separator()
- fileMenu.add_command(label="Exit", command=_quit)
- menuBar.add_cascade(label="File", menu=fileMenu)
-
- helpMenu= Menu(menuBar, tearoff=0)
- helpMenu.add_command(label="About")
- menuBar.add_cascade(label="Help", menu=helpMenu)
-
- win.mainloop()
About the code
- First, I am importing the tkinter modules.
- Next, I assign a class and variables and give application title.
- Next, I create Menu bar and adding menus into the menu bar like file, help.
- Next, I create menu items and items event into the menus like new, exit
- Finally, I have started Windows event loop by calling the mainloop method.
- And, I execute the code.
Output