Python Forum
[Tkinter] sleep(n) not working inside tkinter mainloop - Printable Version

+- Python Forum (
+-- Forum: Python Coding (
+--- Forum: GUI (
+--- Thread: [Tkinter] sleep(n) not working inside tkinter mainloop (/Thread-Tkinter-sleep-n-not-working-inside-tkinter-mainloop)

sleep(n) not working inside tkinter mainloop - roger31415 - Jul-14-2019

Hello and thanks in advance for any help. I've reproduced an issue present in complex code, in much simpler test code shown below that illustrates the fundamental issue. When this code executes, "A", "B", and "C" are displayed on the console from the print statements with a five second delay between A and B, and B and C, as expected. However when the test_function executes, after the total ten second delay, the tkinter window then appears with only "C" displayed, skipping the display of "A" and "B". The expectation was that the window would first appear with "A", and then after five seconds, the label would change to "B" and then after another five seconds it would change to "C".

I also get the same result if instead of calling test_function(), I replace the function call with the code itself. Also, if I invoke the window first displaying some other unrelated widget, and then try to display the label widget with the same sleep scenario, only the final label text assignment "C" is shown, and never "A" or "B".

I'm a new Python coder, and I'm sure I'm missing something very fundamental, perhaps related to blocking? The sleep delay functionality will ultimately be used (with much shorter durations) to pulse Raspberry Pi output ports when various tkinter buttons are clicked. Here's the test code, and thanks again!

from time import sleep
from tkinter import *

w = Tk()
w.title("sleep test")

test_label=Label(w, text="A")
test_label.grid(column=0, row=0)

def test_function():




RE: sleep(n) not working inside tkinter mainloop - Yoriz - Jul-14-2019

Please see the following forum thread for a tutorial showing how to use sleep (blocking code) with tkinter.

RE: sleep(n) not working inside tkinter mainloop - wuf - Jul-14-2019

Hi roger31415

Here one variant without using time.sleep:
from tkinter import *

def display_loop(data, index=0):
    display_item = data[index]
    delay, text = display_item
    index += 1
    if index == len(data): return
    main_win.after(delay, display_loop, data, index)

main_win = Tk()
main_win.title("Delay Test")
test_label=Label(main_win, font=('Helvetica', 20, 'bold'))
test_label.grid(column=0, row=0)

data = [[5000, 'A'], [5000, 'B'], [0, 'C']]
wuf :-)