Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What does the 'tearoff' attribute do in a Tkinter Menu?
The tearoff attribute in Tkinter Menu controls whether a menu can be "torn off" or detached from its parent window. When enabled, users can separate the menu into a floating window for easier access.
Tearoff Options
The tearoff attribute accepts a Boolean value with two behaviors:
tearoff=0 − Menu remains attached to the parent window (default)
tearoff=1 − Menu displays a dashed separator line at the top, allowing users to detach it
Example: Non-Tearable Menu
Here's how to create a menu that stays attached to the window:
import tkinter as tk
from tkinter import *
win = Tk()
win.title("Non-Tearable Menu Example")
win.geometry("400x300")
def show_message():
label = Label(win, text="Menu item selected!", font=('Arial', 14))
label.pack(pady=20)
# Create menubar
menu_bar = Menu(win)
# Create non-tearable menu (tearoff=0)
file_menu = Menu(menu_bar, tearoff=0)
file_menu.add_command(label="New", command=show_message)
file_menu.add_command(label="Open", command=show_message)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=win.quit)
menu_bar.add_cascade(label="File", menu=file_menu)
win.config(menu=menu_bar)
win.mainloop()
Example: Tearable Menu
Now let's create a menu that can be detached from the window:
import tkinter as tk
from tkinter import *
win = Tk()
win.title("Tearable Menu Example")
win.geometry("400x300")
def show_message():
label = Label(win, text="Menu item selected!", font=('Arial', 14))
label.pack(pady=20)
# Create menubar
menu_bar = Menu(win)
# Create tearable menu (tearoff=1)
file_menu = Menu(menu_bar, tearoff=1)
file_menu.add_command(label="New", command=show_message)
file_menu.add_command(label="Open", command=show_message)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=win.quit)
menu_bar.add_cascade(label="File", menu=file_menu)
win.config(menu=menu_bar)
win.mainloop()
Visual Difference
With tearoff=1, you'll notice a dashed line (----) at the top of the menu. Clicking this line detaches the menu into a separate floating window that remains accessible even when clicking elsewhere.
Common Use Cases
Most modern applications use tearoff=0 to maintain a clean interface. Tearable menus (tearoff=1) are useful when:
Users frequently access the same menu items
Creating floating toolbars or palettes
Building applications where menu access should persist
Conclusion
The tearoff attribute controls menu detachment behavior in Tkinter. Use tearoff=0 for standard menus and tearoff=1 when you want users to create floating menu windows.
