使用Tkinter在GIF中播放动画

Ziz*_*212 11 python animation tkinter gif

我一直在尝试使用动画gif Tkinter.PhotoImage,但没有看到任何成功.它显示图像,但不显示动画.以下是我的代码:

root = Tkinter.Tk()
photo = Tkinter.PhotoImage(file = "path/to/image.gif")
label = Tkinter.Label(image = photo)
label.pack()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

它在窗口中显示图像,就是这样.我认为这个问题与Tkinter.Label我有关,但我不确定.我找了解决方案,但他们都告诉我使用PIL(Python Imaging Library),这是我不想使用的东西.

有了答案,我创建了一些代码(仍然无效......),这里是:

from Tkinter import *

def run_animation():
    while True:
        try:
            global photo
            global frame
            global label
            photo = PhotoImage(
                file = photo_path,
                format = "gif - {}".format(frame)
                )

            label.configure(image = nextframe)

            frame = frame + 1

        except Exception:
            frame = 1
            break

root = Tk()
photo_path = "/users/zinedine/downloads/091.gif"

photo = PhotoImage(
    file = photo_path,
    )
label = Label(
    image = photo
    )
animate = Button(
    root,
    text = "animate",
    command = run_animation
    )

label.pack()
animate.pack()

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

谢谢你的一切!:)

pat*_*yts 8

你必须自己在Tk开动动画.动画gif由单个文件中的多个帧组成.Tk加载第一帧,但您可以通过在创建图像时传递索引参数来指定不同的帧.例如:

frame2 = PhotoImage(file=imagefilename, format="gif -index 2")
Run Code Online (Sandbox Code Playgroud)

如果将所有帧加载到单独的PhotoImages中,然后使用计时器事件切换显示的帧(label.configure(image=nextframe)).计时器的延迟可让您控制动画速度.没有提供任何内容可以为您提供图像中的帧数,而不是一旦超出帧数就无法创建帧.

有关官方字词,请参见照片 Tk手册页.

  • 听起来像[Kludge](https://en.wikipedia.org/wiki/Kludge). (3认同)

小智 5

这是一个没有创建对象的简单示例:

from tkinter import *
import time
import os
root = Tk()

frames = [PhotoImage(file='mygif.gif',format = 'gif -index %i' %(i)) for i in range(100)]

def update(ind):

    frame = frames[ind]
    ind += 1
    label.configure(image=frame)
    root.after(100, update, ind)
label = Label(root)
label.pack()
root.after(0, update, 0)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

  • 你可以解释你的代码,以便其他人可以从中学习,而不是复制和粘贴一些可能或可能不起作用的代码吗? (4认同)
  • @Apostolos:这是因为您尝试加载 100 帧,但是您使用的 gif 不到 100 帧。尝试将 100 帧减少到 10 帧,然后逐渐增加,直到出现错误。 (2认同)