Search code examples
pythonloopstkinterpython-2.xmessagebox

How to close tkintermessagebox when it's running inside a loop?


I'm trying to make the tkinter message box appears every X seconds, and I succeeded in that but the messagebox isn't closing after pressing the cancel button, how can I fix that?

here is the code:

import Tkinter as tk
import tkMessageBox, time

root = tk.Tk()
root.withdraw()
tkMessageBox.showinfo('TITLE', 'FIRST MESSAGE')

def f():
    tkMessageBox.showinfo('TITLE', 'SECOND MESSAGE')
    tkMessageBox.showinfo('TITLE', 'THIRD MESSAGE')
    time.sleep(15)
while True:
    f()

Solution

  • The sleep call freezes the application. You can use the after method to repeat a function call.

    import Tkinter as tk
    import tkMessageBox, time
    
    root = tk.Tk()
    root.withdraw()
    tkMessageBox.showinfo('TITLE', 'FIRST MESSAGE')
    
    def f():
        tkMessageBox.showinfo('TITLE', 'SECOND MESSAGE')
        tkMessageBox.showinfo('TITLE', 'THIRD MESSAGE')
        root.after(15000, f) # call f() after 15 seconds
        
    f()
    
    input('Press Enter to exit')   # or root.mainloop()