How do I handle the window close event in Tkinter?

TkinterPythonServer Side ProgrammingProgramming

Tkinter provides a custom handler to close the window. It acts as a callback function that the user can run in order to close the window.

To close the window using the handler, we can use the destroy() method. It closes the window abruptly after calling it in any function or any widget. Let us invoke the close event handler by defining a method.

By using as an argument in Widget

Example

#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 arguments in command as a function name
my_button= Button(win, text= "X", font=('Helvetica bold', 20),
borderwidth=2, command= win.destroy)
my_button.pack(pady=20)

win.mainloop()

By Invoking in a function

#Importing the required library
from tkinter import *

#Create an instance of tkinter frame or window
win= Tk()

#Set the geometry
win.geometry("600x300")

#Define a function

def close():
   win.destroy()

#Create a button and pass arguments in command as a function name
my_button= Button(win, text= "X", font=('Helvetica bold', 20),
borderwidth=2, command= close)
my_button.pack(pady=20)

win.mainloop()

Output

Running the above code will create a button “X” and by clicking over that, we can close the main window.

raja
Published on 27-Mar-2021 06:08:55
Advertisements