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
Selected Reading
destroy() method in Tkinter - Python
The destroy() method in Tkinter removes a widget from the screen and frees up memory. It's essential for controlling widget behavior and cleaning up GUI components when they're no longer needed.
Syntax
widget.destroy()
Where widget can be any Tkinter widget including windows, buttons, labels, frames, etc.
Example - Button Destruction Chain
This example demonstrates how buttons can destroy each other and the main window ?
from tkinter import *
from tkinter.ttk import *
# Create main window
base = Tk()
base.title("Destroy Method Demo")
base.geometry("300x250")
# Button that closes the entire window
button_1 = Button(base, text="I close the Window", command=base.destroy)
button_1.pack(pady=40)
# Button that destroys the first button
button_2 = Button(base, text="I close the first button", command=button_1.destroy)
button_2.pack(pady=40)
# Button that destroys the second button
button_3 = Button(base, text="I close the second button", command=button_2.destroy)
button_3.pack(pady=40)
base.mainloop()
How It Works
When you click each button:
-
Button 1: Calls
base.destroy()and closes the entire application -
Button 2: Calls
button_1.destroy()and removes Button 1 from the window -
Button 3: Calls
button_2.destroy()and removes Button 2 from the window
Practical Use Cases
Common scenarios where destroy() is useful:
- Closing dialog boxes after user confirmation
- Removing temporary widgets from the interface
- Implementing dynamic UI changes
- Memory cleanup in long-running applications
Example - Dynamic Widget Removal
from tkinter import *
root = Tk()
root.title("Dynamic Widget Removal")
def remove_label():
if 'info_label' in globals():
info_label.destroy()
print("Label removed!")
def create_label():
global info_label
info_label = Label(root, text="This label can be destroyed", bg="yellow")
info_label.pack(pady=10)
Button(root, text="Create Label", command=create_label).pack(pady=5)
Button(root, text="Remove Label", command=remove_label).pack(pady=5)
Button(root, text="Exit", command=root.destroy).pack(pady=5)
root.mainloop()
Conclusion
The destroy() method is essential for proper memory management and dynamic UI control in Tkinter applications. Use it to remove widgets when they're no longer needed or to implement interactive behaviors.
Advertisements
