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
How do I get rid of the Python Tkinter root window?
Sometimes while testing a Tkinter application, you may need to hide or close the default root window. Python Tkinter provides two main methods: destroy() to permanently close the window and withdraw() to temporarily hide it.
Using destroy() Method
The destroy() method permanently closes the Tkinter window and terminates the application ?
from tkinter import *
# Create an instance of window
win = Tk()
win.geometry("700x400")
def close_window():
win.destroy()
# Create a Label
Label(win, text="Type Something", font=('Helvetica bold', 25),
fg="green").pack(pady=20)
# Create a Text widget
text = Text(win, height=10, width=40)
text.pack()
# Create a Quit Button
Button(win, text="Quit", command=close_window, fg="white",
bg="black", width=20).pack(pady=20)
win.mainloop()
Using withdraw() Method
The withdraw() method hides the window from the screen but keeps it in memory. You can restore it later using deiconify() ?
from tkinter import *
# Create an instance of window
win = Tk()
win.geometry("700x400")
def hide_window():
win.withdraw()
def show_window():
win.deiconify()
# Create buttons
Button(win, text="Hide Window", command=hide_window,
bg="red", fg="white", width=15).pack(pady=10)
Button(win, text="Show Window", command=show_window,
bg="green", fg="white", width=15).pack(pady=10)
win.mainloop()
Hiding Root Window at Startup
You can hide the root window immediately when the application starts ?
from tkinter import *
# Create root window
root = Tk()
# Hide the root window immediately
root.withdraw()
# Create a popup dialog instead
from tkinter import messagebox
messagebox.showinfo("Hidden Root", "The root window is hidden!")
# Optionally show it again
root.deiconify()
root.geometry("300x200")
Label(root, text="Root window is now visible").pack(pady=50)
root.mainloop()
Comparison
| Method | Action | Reversible? | Best For |
|---|---|---|---|
destroy() |
Permanently closes window | No | Exiting application |
withdraw() |
Hides window temporarily | Yes (use deiconify()) |
Temporarily hiding window |
Conclusion
Use destroy() to permanently close the Tkinter window and exit the application. Use withdraw() to temporarily hide the window while keeping it accessible for later use.
Advertisements
