Python TKinter Creating Menu & MenuItems – In this Python TKinter article i want to show
you Creating Menu & MenuItems. so first you can watch my previous article on Python TKinter
GUI Development.
Also you can read more articles on Python GUI Development
1: PyQt5 GUI Development Tutorials
2: Pyside2 GUI Development Tutorials
3: wxPython GUI Development Tutorials
4: Kivy GUI Development Tutorials
This is the complete source code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
import tkinter as tk from tkinter import ttk from tkinter import Menu class App(tk.Tk): def __init__(self): super(App, self).__init__() self.title("Menus") self.minsize(600,400) self.wm_iconbitmap('icon.ico') self.createMenu() def createMenu(self): menuBar = Menu(self) self.config(menu = menuBar) file_menu = Menu(menuBar, tearoff = 0) menuBar.add_cascade(label="File", menu=file_menu) file_menu.add_command(label='New') file_menu.add_command(label='Exit') file_menu.add_separator() file_menu.add_command(label="Open") # Add Another Menu to Menbar help_menu = Menu(menuBar, tearoff = 0) menuBar.add_cascade(label = 'Help', menu = help_menu) help_menu.add_command(label = 'About') app = App() app.mainloop() |
These are the imports that we need for this article, basically it is tkinter library, also we are
going to import ttk from tkinter , with Menu.
1 2 3 |
import tkinter as tk from tkinter import ttk from tkinter import Menu |
So in this part we have used Object Oriented Programming (OOP), we have created a class that extends from tk.TKand we have added our window title, window size and window icon in the constructor of the class, make sure that you have added an icon to your working directory . also we have called our def createMenu() method in this class.
1 2 3 4 5 6 7 8 |
class App(tk.Tk): def __init__(self): super(App, self).__init__() self.title("Menus") self.minsize(600,400) self.wm_iconbitmap('icon.ico') self.createMenu() |
So in this method first we have created the object of Menu. and also have we created a
file menu and we add some menuitem like new, exit and open to our File menu.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
def createMenu(self): menuBar = Menu(self) self.config(menu = menuBar) file_menu = Menu(menuBar, tearoff = 0) menuBar.add_cascade(label="File", menu=file_menu) file_menu.add_command(label='New') file_menu.add_command(label='Exit') file_menu.add_separator() file_menu.add_command(label="Open") # Add Another Menu to Menbar help_menu = Menu(menuBar, tearoff = 0) menuBar.add_cascade(label = 'Help', menu = help_menu) help_menu.add_command(label = 'About') |
Run the complete code and this will be the result.
Also you can watch the complete video tutorial for this article
Subscribe and Get Free Video Courses & Articles in your Email