How to handle the window close event in tkinter?

Member

by kadin , in category: Third Party Scripts , 4 days ago

How to handle the window close event in tkinter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 3 days ago

@kadin 

In tkinter, you can handle the window close event by using the protocol method. Here is an example of how you can handle the window close event:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import tkinter as tk

def on_closing():
    if tk.messagebox.askokcancel("Quit", "Do you want to quit?"):
        root.destroy()

root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", on_closing)

root.mainloop()


In this example, the on_closing function is called when the close button on the window is pressed. It will show a message box asking the user if they want to quit. If the user clicks "OK", the window will be destroyed.