Create Menu Bar In Python GUI Application

Introduction

 
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 the "Exit item" in the File menu, the Python application will close.
 
Software requirement
 
Python 3.5 and IDLE (Python 3.5)
 
Programming code
  1. #Create Menubar in Python GUI Application  
  2. import tkinter as tk  
  3. from tkinter import ttk  
  4. from tkinter import Menu  
  5. win = tk.Tk()  
  6. win.title("Python GUI App")  
  7. #Exit action  
  8. def _quit():  
  9.    win.quit()  
  10.    win.destroy()  
  11.    exit()  
  12. #Create Menu Bar  
  13. menuBar=Menu(win)  
  14. win.config(menu=menuBar)  
  15. #File Menu  
  16. fileMenu= Menu(menuBar, tearoff=0)  
  17. fileMenu.add_command(label="New")  
  18. fileMenu.add_separator()  
  19. fileMenu.add_command(label="Exit", command=_quit)  
  20. menuBar.add_cascade(label="File", menu=fileMenu)  
  21. #Help Menu  
  22. helpMenu= Menu(menuBar, tearoff=0)  
  23. helpMenu.add_command(label="About")  
  24. menuBar.add_cascade(label="Help", menu=helpMenu)  
  25. #Calling Main()  
  26. win.mainloop()  
About the code 
  • First, I am importing the tkinter modules.
  • Next, I assign a class and variables and give the application title.
  • Next, I create a 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 the Windows event loop by calling the mainloop method. 
  • And, I execute the code.
Output