2011-10-31 586 views
4

有什麼方法可以在使用Python圖像庫的Tkinter中顯示動畫GIF嗎?python tkinter使用PIL顯示動畫GIF

我認爲ImageSequence module將是這樣做的方式,但我不知道如何使用它,如果可能的話。

第一個問題是,如果有任何簡單的方法。例如:使用PIL和ImageSequence加載GIF,並使用ImageTk.PhotoImage將它繪製在Tkinter窗口上,並將其製作爲動畫。

或者我必須自己設置一個函數,使用after方法或類似time.sleep來循環遍歷GIF幀並在tkinter窗口上繪製它們?

第二個問題:即使我必須做一個函數來循環GIF幀,ImageSequence模塊應該這樣做還是PIL有另一個模塊呢?

我使用的是Python 3.1和private port of PIL,如topic所示。

回答

6

新聞組:comp.lang.python的

來源: 「弗雷德裏克Lundh開發」

日期:星期一,2006年

丹尼爾Nogradi寫道5月1日:

「的源代碼發佈1.1.4版本的腳本中包含腳本 目錄,您可以在其中找到player.py,gifmaker.py和explode.py ,這些都涉及動畫gif。

他們仍然裝運1.1.5(和1.1.6),他們應該工作。

如果你錯過是從腳本目錄中的幾個文件,你可以得到 他們在這裏:

http://svn.effbot.org/public/pil/Scripts/


player.py從從命令行運行

看看這一個是否適合你:

from Tkinter import * 
from PIL import Image, ImageTk 


class MyLabel(Label): 
    def __init__(self, master, filename): 
     im = Image.open(filename) 
     seq = [] 
     try: 
      while 1: 
       seq.append(im.copy()) 
       im.seek(len(seq)) # skip to next frame 
     except EOFError: 
      pass # we're done 

     try: 
      self.delay = im.info['duration'] 
     except KeyError: 
      self.delay = 100 

     first = seq[0].convert('RGBA') 
     self.frames = [ImageTk.PhotoImage(first)] 

     Label.__init__(self, master, image=self.frames[0]) 

     temp = seq[0] 
     for image in seq[1:]: 
      temp.paste(image) 
      frame = temp.convert('RGBA') 
      self.frames.append(ImageTk.PhotoImage(frame)) 

     self.idx = 0 

     self.cancel = self.after(self.delay, self.play) 

    def play(self): 
     self.config(image=self.frames[self.idx]) 
     self.idx += 1 
     if self.idx == len(self.frames): 
      self.idx = 0 
     self.cancel = self.after(self.delay, self.play)   


root = Tk() 
anim = MyLabel(root, 'animated.gif') 
anim.pack() 

def stop_it(): 
    anim.after_cancel(anim.cancel) 

Button(root, text='stop', command=stop_it).pack() 

root.mainloop() 
+0

謝謝,但我是一個雙對Python新手,我該如何真正使用腳本?我已經導入了tkinter,PIL和player,並且已經打開了圖像,我嘗試了'animation = player.UI(root,im)'和一些變體。播放器腳本中的UI類是否爲標籤?當我嘗試打包()它時,它說「UI對象沒有屬性tk」,如果我不包裝()或網格(),則什麼都不會發生。 –