Tkinter message box pops up before other actions

Question:

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()
Asked By: say

||

Answers:

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()
Answered By: cdlane

The proper way to print on messagebox.showinfo in line 10 as above.

messagebox.showinfo(f"The count is", f"count {value}")

Output:

enter image description here

Answered By: toyota Supra
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.