简体   繁体   中英

Tkinter .after() freezes window

I'm trying to make a script with tkinter that displays some elements one after each other (not all of them at the same time) using.after().

The problem I have is that all elements are displayed at the same time after the overall waiting time has finished (overall waiting time = sum of the individual time of each element).

I've checked many examples on the web, and I guess I'm using the.after() method wrong, but I just can't figure out why.

I would expect the following code to update the label wait for 0.5 seconds after each loop. Nonetheless, what I get is a total wait of 3 seconds, after which the tkinter window appears, showing the last element of the list.

import tkinter as tk
import random

grid = [1, 2, 3, 4, 5, 6]

root = tk.Tk()

canvas = tk.Canvas(root, width=200, height=200)
canvas.pack()

def refresh():
    for i in range(len(grid)):
        text = grid[i]
        label.configure(text=text)

        root.after(500)

label = tk.Label(canvas, text='0', font='Courier 18')
label.place(relx=0.45, rely=0.4)

refresh()

root.mainloop()

Thanks in advance!

Yes, it's quite normal, but you have to add an handler after the time delay. If you don't, the computer only freezes the program until the time runs out.

Try this:

root.after(500, handler)

And what does it does is you create a function for the handler and after the 500ms the program will call that function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM