Search code examples
pythontkintermessagebox

Tkinter message box pops up before other actions


I'm struggling with figuring out how to make the messagebox pop up at the right moment. It always seems to pop up before the window updates to show what I want it to. Here's an example; I want the button's text to update to 3 before the messagebox pops up, but it always updates after I click OK on the messagebox.

 from tkinter import *
 from tkinter import messagebox

 win = Tk()
 count = 0


 def click():
     global count
     count += 1
     btn.config(text=count)
     if count == 3:
         messagebox.showinfo('The count is 3')


 btn = Button(text='', command=click)
 btn.pack()

 win.mainloop()

Solution

  • Running your example code, I see the same behavior you describe. I was able to work around it by adding a call to win.update() before the call to messagebox.showinfo(). Full code below though I changed count from a primitive int to an IntVar which doesn't have any effect on your issue, I just wanted to see it if would:

    from tkinter import *
    from tkinter import messagebox
    
    def click():
        count.set(value := count.get() + 1)
    
        if value == 3:
            win.update()
    
            messagebox.showinfo(f"The count is {value}")
    
    win = Tk()
    
    count = IntVar(win, value=0)
    
    Button(win, command=click, textvariable=count).pack()
    
    win.mainloop()