Search code examples
python-3.xtkinterttk

How to run a function as soon as GUI started?


I need to run a check function as soon as the tkinter GUI is available. I tried with the following code, but the Messagebox which comes up is unresponsive and I can't press the OK button.

import tkinter.messagebox as mbox
import tkinter
from tkinter import ttk



class MQ(ttk.Frame):
    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)

        self.root = parent
        self.init_gui()
        if mycheck=True:
            mbox.showinfo("Title","message")

...
...
if __name__ == '__main__':
    root = tkinter.Tk()
    MQ(root)
    root.mainloop()

Solution

  • You can use after_idle to run something as soon as the GUI starts up, or you can use after to have it run after a brief amount of time. The two have slightly different behaviors with respect to whether the code runs before or after the root window is displayed (which might be platform dependent; I'm not sure)

    import tkinter as tk
    from tkinter import messagebox
    
    def say_hello(root, message):
        tk.messagebox.showinfo("Info", message)
    
    root = tk.Tk()
    root.after(1, say_hello, root, "Hello, world")
    
    root.mainloop()