使用Tkinter在GIF中播放动画 [英] Play Animations in GIF with Tkinter

查看:534
本文介绍了使用Tkinter在GIF中播放动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been trying to play an animated gif using Tkinter.PhotoImage, but haven't been seeing any success. It displays the image, but not the animation. The following is my code:

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

它在窗口中显示图像,仅此而已。我认为该问题与 Tkinter.Label 有关,但我不确定。我一直在寻找解决方案,但是它们都告诉我要使用PIL(Python影像库),而这是我不想使用的东西。

It displays the image in a window, and that's it. I'm thinking that the issue has something to do with Tkinter.Label but I'm not sure. I've looked for solutions but they all tell me to use PIL (Python Imaging Library), and it's something that I don't want to use.

有了答案,我创建了更多代码(仍然不起作用...),这里是:

With the answer, I created some more code (which still doesn't work...), here it is:

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()

感谢一切! :)

推荐答案

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

You have to drive the animation yourself in Tk. An animated gif consists of a number of frames in a single file. Tk loads the first frame but you can specify different frames by passing an index parameter when creating the image. For example:

frame2 = PhotoImage(file=imagefilename, format="gif -index 2")

如果将所有帧加载到单独的PhotoImages中,然后使用计时器事件切换显示的帧( label.configure(image = nextframe))。计时器上的延迟使您可以控制动画速度。除了超出帧数后无法创建帧,没有任何东西可提供给您图像中的帧数。

If you load up all the frames into separate PhotoImages and then use timer events to switch the frame being shown (label.configure(image=nextframe)). The delay on the timer lets you control the animation speed. There is nothing provided to give you the number of frames in the image other than it failing to create a frame once you exceed the frame count.

请参见照片 Tk手册中的官方单词。

See the photo Tk manual page for the official word.

这篇关于使用Tkinter在GIF中播放动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆