Open In App

What does the ‘tearoff’ attribute do in a Tkinter Menu?

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite:

Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is an easy task.

Important Terminologies

  • Menu is used to create various types of menus such as top level, pull down etc.. in Tkinter. The Top Level Menu, which is displayed under the title bar of main window.

Syntax:

To create menu

menubar = Menu(root)

To add text in Menu

file = Menu(menubar) 
menubar.add_cascade(label ='Your Text', menu = file)
  • A Tearoff permits you to detach menus for the most window making floating menus. If you produce a menu you may see dotted lines at the top after you click a top menu item. To fix this tearoff needs to set to 0 at the time of menu declaration.
file = Menu(menubar,tearoff=0)
edit = Menu(menubar,tearoff=0)
help_ = Menu(menubar,tearoff=0)
  • Cascade is used to create Sub-menus below the Main-menu.
  • A submenu is a menu plugged into another menu object. By adding the menu to the fileMenu and not to the menubar, we create a submenu.

Syntax:

Object_Name.add_command(label ='Write Text')

Approach

  • Import module
  • Create normal Tkinter window
  • Add Menus
  • Add SubMenus

Program:

Python3




# import Module
from tkinter import *
  
# creating tkinter window
root = Tk()
  
# set geometry
root.geometry("400x400")
  
# Add title
root.title('Menu Demonstration')
  
# Creating Menubar
menubar = Menu(root)
  
# Adding File Menu and SubMenus
file = Menu(menubar, tearoff=0)
menubar.add_cascade(label='File', menu=file)
file.add_command(label='New File')
file.add_command(label='Open...')
file.add_command(label='Save')
  
# Adding Edit Menu and SubMenus
edit = Menu(menubar, tearoff=0)
menubar.add_cascade(label='Edit', menu=edit)
edit.add_command(label='Cut')
edit.add_command(label='Copy')
edit.add_command(label='Paste')
edit.add_command(label='Select All')
  
# Adding Help Menu and SubMenus
help_ = Menu(menubar, tearoff=0)
menubar.add_cascade(label='Help', menu=help_)
help_.add_command(label='Tk Help')
help_.add_command(label='Demo')
  
# display Menu
root.config(menu=menubar)
  
# Execute Tkinter
root.mainloop()


Output:

Without Using tearoff method

 

Output: 

 With tearoff method



Last Updated : 11 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads