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

查看:91
本文介绍了使用 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()

谢谢你所做的一切!:)

Thanks for everything! :)

推荐答案

您必须在 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.

请参阅 photo Tk 手册页了解官方说法.

See the photo Tk manual page for the official word.

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

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