Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

python - Slow animation in tkinter

label = Label(screen, image = "")
label.pack()
num = 0

num = 0
img = None
def animate():
    global num
    global img
    img = PhotoImage(file = "gif.gif", format = "gif -index {}".format(num))
    label.configure(image = img)
    num = (num+1)%180
    screen.after(1, animate)
animate()

screen.mainloop()

The animation itself works, but it gets slower and slower considering I put a delay of 1 millisecond. A recommended solution would be not to import other libraries, but go ahead if u know it helps.

question from:https://stackoverflow.com/questions/65901181/slow-animation-in-tkinter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Whilst I didn't see the animation get slower, it did use a lot of memory. I found loading the frames first and then animating the image resulted in much lower memory usage, as you are not opening and processing an image every millisecond.
Here is the amended code:

label = Label(screen, image = "")
label.pack()
num = 0
img = None
frames = [PhotoImage(file = "gif.gif", format = "gif -index {}".format(num)) for num in range(180)]
def animate():
    global num
    global img
    label.configure(image = frames[num])
    num = (num+1)%180
    screen.after(100, animate)
animate()

screen.mainloop()

I would not recommend setting screen.after to 1 millisecond as this makes the gif too fast. I found 100ms was fast enough.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...