'Python 3 closing tkinter messagebox through code

I am new to Python and failing on first hurdle. I have a message box with a canvas with image loaded into it that's triggered to activate via a Passive infrared sensor.

Got everything working but I want the message box to disappear after 5 secs. The time delay isn't a problem but trying to get the message box to go is another thing been using destroy() but nothing.

Understand there are window levels I.e Toplevel. But wondered if someone could point me in the right direction.



Solution 1:[1]

The small function below will do the job. By setting the type you can choose for: info, warning or error message box, the default is 'Info'. You can set also the timeout, the default is 2.5 seconds.

def showMessage(message, type='info', timeout=2500):
    import tkinter as tk
    from tkinter import messagebox as msgb

    root = tk.Tk()
    root.withdraw()
    try:
        root.after(timeout, root.destroy)
        if type == 'info':
            msgb.showinfo('Info', message, master=root)
        elif type == 'warning':
            msgb.showwarning('Warning', message, master=root)
        elif type == 'error':
            msgb.showerror('Error', message, master=root)
    except:
        pass

Call the function as follow: For message type 'Info' and timeout of 2.5 seconds:

showMessage('Your message')

Or by your own settings for type message 'Error' and timeout 4 seconds:

showMessage('Your message', type='error', timeout=4000)

Solution 2:[2]

Without any code to go off of this is the best that I can give you.

This is an object-oriented program and truth be told I just started understanding what they are doing.

However just focus on def create_window(self)

It takes the window instance t which it declared and placed all the info on and .destroy it.

import tkinter as tk

class MainWindow(tk.Frame):
    counter = 0
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.button = tk.Button(self, text="Create new window", command=self.create_window)
        self.button.pack(side="top")

    def create_window(self):
        self.counter += 1
        t = tk.Toplevel(self)
        t.wm_title("Window #%s" % self.counter)
        l = tk.Label(t, text="This is window #%s" % self.counter)
        l.pack()
        b = tk.Button(t, text='close', command=t.destroy)
        b.pack()

if __name__ == "__main__":
    root = tk.Tk()
    main = MainWindow(root)
    main.pack(side="top", fill="both", expand=True)
    root.mainloop()

Hope this helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Tristan Roylance Pillowpants