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 hide a widget after some time in Python Tkinter?
Tkinter is a standard Python library for developing GUI-based applications. We can create games, tools, and other applications using the Tkinter library. To develop GUI-based applications, Tkinter provides widgets.
Sometimes, there might be a requirement to hide a widget for some time. This can be achieved by using the pack_forget(), grid_forget(), or place_forget() methods depending on how the widget was placed. We can also use the after() method to delay the hiding action.
Using pack_forget() Method
When a widget is placed using pack(), use pack_forget() to hide it ?
import tkinter as tk
# Create main window
root = tk.Tk()
root.geometry("400x300")
root.title("Hide Widget Example")
# Create a label widget
label = tk.Label(root, text="This label will disappear in 3 seconds",
font=("Arial", 14), bg="lightblue", pady=20)
label.pack(pady=50)
# Hide the label after 3 seconds
root.after(3000, label.pack_forget)
root.mainloop()
Using grid_forget() Method
For widgets placed using grid(), use grid_forget() method ?
import tkinter as tk
root = tk.Tk()
root.geometry("400x300")
root.title("Grid Forget Example")
# Create button using grid layout
button = tk.Button(root, text="Click me before I disappear!",
font=("Arial", 12), bg="lightgreen")
button.grid(row=0, column=0, padx=50, pady=100)
# Hide button after 4 seconds
root.after(4000, button.grid_forget)
root.mainloop()
Showing Widget Again After Hiding
You can also show the widget again after hiding it using a timer ?
import tkinter as tk
root = tk.Tk()
root.geometry("400x300")
root.title("Hide and Show Example")
# Create a frame with text
frame = tk.Frame(root, bg="yellow", width=200, height=100)
frame.pack(pady=80)
label = tk.Label(frame, text="Watch me disappear and reappear!",
font=("Arial", 11), bg="yellow")
label.pack(pady=30)
def hide_and_show():
# Hide after 2 seconds
root.after(2000, frame.pack_forget)
# Show again after 5 seconds
root.after(5000, lambda: frame.pack(pady=80))
# Start the hide/show cycle
hide_and_show()
root.mainloop()
Method Comparison
| Layout Manager | Hide Method | Show Method |
|---|---|---|
pack() |
pack_forget() |
pack() |
grid() |
grid_forget() |
grid() |
place() |
place_forget() |
place() |
Conclusion
Use the appropriate forget method based on your layout manager: pack_forget(), grid_forget(), or place_forget(). Combine with after() method to create timed hiding effects in your Tkinter applications.
