sathvik a
sathvik a

Reputation: 38

How do I display a message before closing the tkinter window?

A message is required to be shown just before closing the tkinter window on the click of a close button added to the window.

lab = Label(window,text = 'thank you')
lab.grid()
window.destroy()

I used the above code to do so, but the window gets closed before the message is being displayed Can I have the solution for this?

Upvotes: 0

Views: 2494

Answers (1)

Matiiss
Matiiss

Reputation: 6156

You can either use this:

from tkinter import Tk
import tkinter.messagebox as msgbox


def display_msg():
    msgbox.showinfo(title='', message='Thank You')
    root.destroy()


root = Tk()

root.protocol('WM_DELETE_WINDOW', display_msg)

root.mainloop()

which will show You a messagebox before closing, or if You want to display a widget use this:

from tkinter import Tk, Label


def display_msg():
    msg = Label(root, text='Thank You!')
    msg.pack()
    root.after(3000, root.quit)


root = Tk()

root.protocol('WM_DELETE_WINDOW', display_msg)

root.mainloop()

When You protocol root with 'WM_DELETE_WINDOM' You can make it execute a function when You try to close the window.

In the first example it will just show an infobox.

In the second example it will wait for 3 seconds (3000 miliseconds) and then destroy the root

Upvotes: 3

Related Questions