How To Get Rid Of Python Tkinter Root Window?
Python’s Tkinter library offers a simple and effective way to create graphical user interfaces (GUIs) for your applications. However, when using Tkinter, you may encounter situations where you need to close or remove the root window, which is the main window of your GUI. Whether you’re looking to clean up your interface or transition to another window, knowing how to properly get rid of the Tkinter root window is essential. In this guide, we’ll explore methods to achieve this efficiently.
Get Rid Of Python Tkinter Root Window
Example 1: Using the destroy() Method
In this example, we create a Tkinter root window and define a function close_window() that calls the destroy() method on the root window object. This method terminates the main loop and destroys all widgets contained within the root window, effectively closing the window and ending the application.
import tkinter as tk
def close_window():
root.destroy()
root = tk.Tk()
root.title("Root Window")
# Create widgets and layout here
close_button = tk.Button(root, text="Close Window", command=close_window)
close_button.pack()
root.mainloop()
Output:
Example 2: Customizing Close Behavior
In this example, we use the protocol() method to customize the behavior when the user attempts to close the window using the window manager’s close button (e.g., clicking the “X” button on the window). We define the on_closing() function to ask the user for confirmation before closing the window. If the user confirms, the root window is destroyed.
import tkinter as tk
def on_closing():
if tk.messagebox.askokcancel("Quit", "Do you want to quit?"):
root.destroy()
root = tk.Tk()
root.title("Root Window")
# Create widgets and layout here
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
Output: