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
How to clear out a frame in the Tkinter?
Tkinter frames are used to group and organize widgets in an aesthetic way. A frame component can contain Button widgets, Entry widgets, Labels, ScrollBars, and other widgets.
If we want to clear the frame content or delete all the widgets inside the frame, we can use the destroy() method. This method can be invoked by targeting the children of the frame using winfo_children().
Syntax
for widget in frame.winfo_children():
widget.destroy()
Example
Here's a complete example showing how to clear all widgets from a frame ?
# Import the required libraries
from tkinter import *
# Create an instance of tkinter frame
win = Tk()
# Set the geometry of frame
win.geometry("600x250")
# Create a frame
frame = Frame(win)
frame.pack(side="top", expand=True, fill="both")
# Create a text label
Label(frame, text="Enter the Password", font=('Helvetica', 20)).pack(pady=20)
def clear_frame():
for widgets in frame.winfo_children():
widgets.destroy()
# Create a button to close the window
Button(frame, text="Clear", font=('Helvetica bold', 10), command=clear_frame).pack(pady=20)
win.mainloop()
Output
Running the above code will display a window containing a button "Clear" that targets all the widgets inside the frame and clears it.
Now click on the "Clear" Button and it will clear all the widgets inside the frame.
How It Works
The winfo_children() method returns a list of all child widgets within the frame. The destroy() method permanently removes each widget from the interface and frees up memory.
Alternative Approach
You can also clear specific widgets by referencing them directly ?
# Clear specific widgets label.destroy() button.destroy() # Or clear and recreate the entire frame frame.destroy() frame = Frame(win) frame.pack(side="top", expand=True, fill="both")
Conclusion
Use winfo_children() with destroy() to clear all widgets from a frame efficiently. This approach is useful for dynamic interfaces where content needs to be refreshed or reset.
