使用tkinter在python中播放动画GIF

发布于 2021-01-29 19:33:58

我想使用python3和tkinter创建一个虚拟的宠物风格游戏。到目前为止,我已经有了主窗口并开始放入标签,但是我遇到的问题是播放动画gif。我在这里搜索并找到了一些答案,但是他们不断抛出错误。我发现使用PhotoImage的结果具有gif的索引位置,并在一定范围内继续。

    # Loop through the index of the animated gif
frame2 = [PhotoImage(file='images/ball-1.gif', format = 'gif -index %i' %i) for i in range(100)]

def update(ind):

    frame = frame2[ind]
    ind += 1
    img.configure(image=frame)
    ms.after(100, update, ind)

img = Label(ms)
img.place(x=250, y=250, anchor="center")

ms.after(0, update, 0)
ms.mainloop()

当我在终端中使用“ pyhton3 main.py”运行此命令时,出现以下错误:

_tkinter.TclError:该索引没有图像数据

我俯视什么或完全忽略了什么?

这是查看完整项目的GitHub存储库的链接:VirtPet_Python

提前致谢!

关注者
0
被浏览
182
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    该错误表示您尝试加载100帧,但是gif小于此数量。

    众所周知,tkinter中的gif动画效果很差。我在很久以前就编写了这段代码,您可以从中窃取,但是除了小gif之外,其他任何东西都不会让您感到la懒:

    import tkinter as tk
    from PIL import Image, ImageTk
    from itertools import count
    
    class ImageLabel(tk.Label):
        """a label that displays images, and plays them if they are gifs"""
        def load(self, im):
            if isinstance(im, str):
                im = Image.open(im)
            self.loc = 0
            self.frames = []
    
            try:
                for i in count(1):
                    self.frames.append(ImageTk.PhotoImage(im.copy()))
                    im.seek(i)
            except EOFError:
                pass
    
            try:
                self.delay = im.info['duration']
            except:
                self.delay = 100
    
            if len(self.frames) == 1:
                self.config(image=self.frames[0])
            else:
                self.next_frame()
    
        def unload(self):
            self.config(image="")
            self.frames = None
    
        def next_frame(self):
            if self.frames:
                self.loc += 1
                self.loc %= len(self.frames)
                self.config(image=self.frames[self.loc])
                self.after(self.delay, self.next_frame)
    
    root = tk.Tk()
    lbl = ImageLabel(root)
    lbl.pack()
    lbl.load('ball-1.gif')
    root.mainloop()
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看