tkinter 中的慢动画 [英] 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()
动画本身可以工作,但考虑到我延迟了 1 毫秒,它变得越来越慢.推荐的解决方案是不要导入其他库,但如果您知道它有帮助,请继续.
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.
推荐答案
虽然我没有看到动画变慢,但它确实使用了大量内存.我发现首先加载帧然后动画图像导致内存使用量低得多,因为您不是每毫秒打开和处理图像.
修改后的代码如下:
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()
我不建议将 screen.after
设置为 1 毫秒,因为这会使 gif 过快.我发现 100 毫秒已经足够快了.
I would not recommend setting screen.after
to 1 millisecond as this makes the gif too fast. I found 100ms was fast enough.
这篇关于tkinter 中的慢动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!