Tkinter showing message before closing the window or terminating the application using protocol
Using protocol
Here the function my_msg() is executed once we try to close the window.
my_w.protocol('WM_DELETE_WINDOW', my_msg)
Inside the function my_msg() we kept the code to display the message box ( commented line ) or we show a message for 3 seconds before closing the window.
import tkinter as tk
from tkinter import *
import tkinter.messagebox as msgbox
my_w = tk.Tk()
my_w.geometry("400x200") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
# create one lebel
l1 = tk.Label(my_w, text='Welcome' )
l1.grid(row=1,column=2)
b1 = tk.Button(my_w, text='Clik me to Close',
command=lambda:my_msg())
b1.grid(row=2,column=2)
def my_msg():
#msgbox.showinfo(title='', message='Thank You') #message box
l2=tk.Label(my_w,text='Thank you')
l2.grid(row=2,column=3) # show message in grid
my_w.after(3000, my_w.quit) # close window after 3 seconds
my_w.protocol('WM_DELETE_WINDOW', my_msg)
my_w.mainloop()
Using child window
import tkinter as tk
from tkinter import *
import tkinter.messagebox as msgbox
my_w = tk.Tk()
my_w.geometry("400x200") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
# create one lebel
my_str = tk.StringVar()
l1 = tk.Label(my_w, textvariable=my_str )
l1.grid(row=1,column=2)
my_str.set("Hi I am main window")
b1 = tk.Button(my_w, text='Clik me to open new window',
command=lambda:my_open())
b1.grid(row=2,column=2)
def my_open():
my_w_child=Toplevel(my_w) # Child window
my_w_child.geometry("400x200") # Size of the window
my_w_child.title("www.plus2net.com")
l1 = tk.Label(my_w_child, text='I am child window' )
l1.grid(row=1,column=2)
def my_msg():
#l2=tk.Label(my_w_child,text='Thank you')
#l2.grid(row=2,column=2)
#my_w_child.after(3000, my_w_child.quit)#close after 3 seconds
msgbox.showinfo(title='', message='Thank You') # show message
my_w_child.destroy()
my_w_child.protocol('WM_DELETE_WINDOW', my_msg)
my_w.mainloop()