0

I try to show a status from a called function in real time. However, the messages appears in the GUI all at ones after function is done. What can I do?

Thanks for your help!

from tkinter import *

import time


def sleep():
    msgbox.insert(INSERT,"go sleep...\n")
    time.sleep(2)
    msgbox.insert(INSERT,"... need another 2 sec \n")
    time.sleep(2)   
    msgbox.insert(INSERT,"... that was good\n")
    return

root = Tk()
root.minsize(600,400)

button= Button(text="Get sleep", command=sleep)
button.place(x=250, y=100,height=50, width=100)

msgbox =Text(root, height=10, width=60)
msgbox.place(x=20, y=200)

mainloop()
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
highbeta
  • 11
  • 1
  • You could learn about [`after()`](https://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.after-method).Sleep will block your code. – jizhihaoSAMA May 24 '20 at 09:46
  • Does this answer your question? [tkinter: how to use after method](https://stackoverflow.com/a/25753719/7414759) – stovfl May 24 '20 at 10:52

1 Answers1

0

You can use the Tk.update() function to update the window without having to wait for the function to finish:

from tkinter import *

import time


def sleep():
    msgbox.insert(INSERT,"go sleep...\n")
    root.update()
    time.sleep(2)
    msgbox.insert(INSERT,"... need another 2 sec \n")
    root.update()
    time.sleep(2)   
    msgbox.insert(INSERT,"... that was good\n")

root = Tk()
root.minsize(600,400)

button= Button(text="Get sleep", command=sleep)
button.place(x=250, y=100,height=50, width=100)

msgbox =Text(root, height=10, width=60)
msgbox.place(x=20, y=200)

mainloop()

(also the return is unnecessary, you use it if you want to end a function partway through or return a value from the function).

Let me know if you have any problems :).

TheFluffDragon9
  • 514
  • 5
  • 11
  • This is exactly what I was looking for! Sometimes you can't see the forest for the trees. Thanks a lot for your help! – highbeta May 24 '20 at 20:22