About Lesson
In this TKinter Tutorial we are going to learn about adding Menu Item Commands, in the previous lesson we have created our menu and menu items, now let’s add a command to the menu item.
We are going to use complete code from the previous lesson, we want to just add exit command to the exit menu item.
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 41 42 43 44 |
from tkinter import * class Window(Tk): def __init__(self): super(Window, self).__init__() self.title("Tkinter Menu") self.minsize(500,400) self.wm_iconbitmap("myicon.ico") self.create_menu() def window_close(self): self.quit() self.destroy() exit() def create_menu(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", command =self.window_close) file_menu.add_separator() file_menu.add_command(labe = "Open") help_menu = Menu(menuBar, tearoff = 0) menuBar.add_cascade(label = "Help", menu = help_menu) help_menu.add_command(label = "About") window = Window() window.mainloop() |
This is the method that is used for closing the window when we pressed the the exit menu item.
1 2 3 4 |
def window_close(self): self.quit() self.destroy() exit() |
We have connected this method with the exit menu item and we have used command for this.
1 |
file_menu.add_command(label = "Exit", command =self.window_close) |
Run the code and this is the result.