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 handle the window close event in Tkinter?
Tkinter provides several ways to handle window close events. You can use the destroy() method directly or create custom close handlers for better control over the closing process.
Using destroy() Method Directly
The simplest approach is to pass destroy() directly to a widget's command parameter ?
# Importing the required library
from tkinter import *
# Create an instance of tkinter frame or window
win = Tk()
# Set the geometry
win.geometry("600x400")
# Create a button and pass destroy method directly
close_button = Button(win, text="Close Window", font=('Helvetica bold', 20),
borderwidth=2, command=win.destroy)
close_button.pack(pady=20)
win.mainloop()
Using a Custom Close Function
For more control, you can define a custom function that handles the close event ?
# Importing the required library
from tkinter import *
# Create an instance of tkinter frame or window
win = Tk()
# Set the geometry
win.geometry("600x400")
# Define a custom close function
def close_window():
print("Closing the window...")
win.destroy()
# Create a button with custom close function
close_button = Button(win, text="Close Window", font=('Helvetica bold', 20),
borderwidth=2, command=close_window)
close_button.pack(pady=20)
win.mainloop()
Handling Window Close Event (X Button)
To handle the window's X button close event, use the protocol() method ?
from tkinter import *
from tkinter import messagebox
# Create window
win = Tk()
win.geometry("600x400")
win.title("Close Event Handler")
def on_closing():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
win.destroy()
# Handle the window close event (X button)
win.protocol("WM_DELETE_WINDOW", on_closing)
# Add some content
label = Label(win, text="Try closing this window with the X button",
font=('Arial', 14))
label.pack(pady=20)
win.mainloop()
Comparison of Methods
| Method | Use Case | Advantage |
|---|---|---|
win.destroy |
Simple close button | Direct and immediate |
| Custom function | Close with actions | Execute code before closing |
protocol() |
Handle X button | Intercepts window close event |
Conclusion
Use destroy() for simple window closing, custom functions for pre-close actions, and protocol("WM_DELETE_WINDOW") to handle the X button close event with confirmation dialogs or cleanup tasks.
Advertisements
