Search code examples
pythontkinterdelay

Why i use .after() to delay call a function in a loop not working properly


Why i use .after() to delay call a function in a loop not working properly. The first loop in .after() delayed call function show_letter() . But after the first loop, it just call the function without any delay.

from tkinter import *
import random
import string

window = Tk()
# window.attributes('-fullscreen', True)


#
def show_letter():
    randomletter = random.choice(string.ascii_letters)

    print(randomletter)
    label.config(text=randomletter)
  


def delay_show():
    for i in range(200):
        window.after(2000, show_letter)


label = Label(window,
              text='',
              font=('arial', 40),
              )


label.place(relx=0.5, rely=.4, )

delay_show()

window.mainloop()

Solution

  • Consider this code:

    def delay_show():
        for i in range(200):
            window.after(2000, show_letter)
    

    What this does is schedule the first call to show_letter in 2 seconds. Then it also schedules the second call in two seconds. Not two seconds after the first call but two seconds after the start of the loop. Then the third call is also two seconds after the start of the loop.

    In other words, all of the calls are all scheduled to start at the same time, in 2 seconds.

    The fix is simple: multiply 2000 times the loop increment so that the first call is in 2 seconds, the next in 4, the next in 6, and so on.

    def delay_show():
        for i in range(200):
            window.after(2000*i, show_letter)