Search code examples
pythontkintersleep

How to use tkinter .after() method to create delay


How to properly use .after() from tkinter to create a delay in between iterations without freezing the entire program until all the iterations are completed.

Example of problem: total of 10 iterations, GUI will not update until the 10 iterations is completed

What I want: GUI to update after every iteration, when calling .after().

I have tried a similar code to the one below, by calling the class after every iteration, but it still freezes.

// example of a similar code i tried
import Tkinter as tk
import time

class App():
def __init__(self):
        self.root = tk.Tk()
        self.label = tk.Label(text="")
        self.label.pack()
        self.update_clock()
        self.root.mainloop()

def update_clock(self):
        now = time.strftime("%H:%M:%S")
        self.label.configure(text=now)
        self.root.after(1000, self.update_clock)

app=App()

// example of my current code
self.board = [1,1,1,1,1,1]

def updateBoard(self, seed, move):
    while seed > 0:
        self.board[move] += 1
        seed = seed - 1
        move = move + 1
        // here i call the function to delay the execution for 1s
        self.createDelay()
        self.displayBoard()

p.s. I tried time.sleep(), it freezes as well.


Solution

  • The clock app you posted works fine, you can do everything the same way. (Basically I got rid of while loop, which freezes your app while it is executing)

    def updateBoard(self, seed, move):
        if seed <= 0:
            return
        self.board[move] += 1
        seed = seed - 1
        move = move + 1
        self.displayBoard()
        # call this function with parameters seed and move after 1000 ms
        root.after(1000, lambda: updateBoard(seed, move))
    

    Why this works: in main loop your window processes some events, or in this case calls a function if 1 second has passed. If you create a function, that runs forever, this main loop won't continue, because it is waiting for your function to finish. That's why the app will freeze.