2017-05-03 1193 views
1

我想用python3和tkinter创建一个虚拟宠物风格的游戏。到目前为止,我有主窗口,并开始放置标签,但我遇到的问题是播放动画GIF。我在这里搜索并找到了一些答案,但他们一直在抛出错误。我发现使用PhotoImage的gif的索引位置在一定范围内持续。用tkinter在python中播放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: no image data for this index

我是什么俯瞰或彻底离开了呢?

这里是链接到GitHub的仓库看到完整的项目:VirtPet_Python

提前感谢!

+1

难道你不应该检查'ind'永远不会超过100吗?也许'ind%= 100'? –

回答

2

这个错误意味着你试图加载100帧,但gif小于这个值。

tkinter中的动画gif非常糟糕。我以前写过这段代码,你可以窃取它,但是对于小GIF文件会产生延迟:

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=None) 
     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() 
+0

这让我想到了......我将范围改为13,因为我创建了这个gif并知道它有多少帧。现在它的负载和终端卡在“索引超出范围”的错误。我调整了下面的函数中的所有其他数字。有什么方法可以计算帧并将其存储在变量中,然后在范围()中调用它? – nmoore146

+0

不,但是你可以循环帧,直到你得到EOF(文件结束)错误,就像我在我的代码中那样。 – Novel

+0

好吧,我编辑了我的代码并将其推送到GitHub。现在它循环遍历13帧,但完整的图像没有显示出来,然后当它通过所有帧时,我得到一个索引超出范围错误。 – nmoore146