What does the 'tearoff' attribute do in a Tkinter Menu?

PythonTkinterGUI-Programming

Using Tkinter.Menu, we can create menus and submenus. Also, there are some other properties which are used with tkinter menus.

Tearoff property makes the menus in the window as tearable. tearoff attribute accepts a Boolean value to separate the menu from the main window or the parent window. With tearoff attribute, we have two options,

  • If tearoff=0, make the menu stick to the Window.

  • If tearoff=1, it display a “----” empty dotted lines on the menus through which we can separate our menu from the window.

Example

#Importing the tkinter library
from tkinter import *
win= Tk()
win.title("Tearoff Example")
win.geometry("600x500")

#Define a Function for Menu Selection Event
def mytext():
   lab= Label(win,text= "You have made a selection", font=('Helvetica',20)).pack(pady=20)

#Create a Menubar
menu_bar = Menu(win)

#Make the menus non-tearable
file_menu = Menu(menu_bar, tearoff=0)

#Tearable Menu
#file_menu= Menu(menu_bar, tearoff=1)
file_menu.add_command(label="New",command=mytext)
# all file menu-items will be added here next
menu_bar.add_cascade(label='File', menu=file_menu)
win.config(menu=menu_bar)

mainloop()

Output

Running the above snippet will generate the output and will show a window which will have a menu.

Thus, for non-tearable and tearable menus (tearoff=0 and tearoff=1), the output will be as follows −

raja
Published on 06-Mar-2021 13:33:50
Advertisements