有什么方法可以使用 Python 图像库在 Tkinter 中显示动画 GIF 吗?
我以为 ImageSequence module将是这样做的方式,但我不知道如何使用它以及是否可能。
第一个问题是有没有简单的方法。例如:使用 PIL 和 ImageSequence 加载一个 GIF,然后使用 ImageTk.PhotoImage
在 Tkinter 窗口上绘制它,它就会被动画化。
或者我是否必须自己设置一个函数,使用 after
方法或类似 time.sleep
的方法循环遍历 GIF 帧并将它们绘制在 tkinter 上 window ?
第二个问题:即使我必须创建一个循环遍历 GIF 帧的函数,ImageSequence 模块是否应该这样做,或者 PIL 有另一个模块吗?
我正在使用 Python 3.1 和 private port of PIL , 在此 topic 中指出.
最佳答案
Newsgroups: comp.lang.python
From: "Fredrik Lundh"
Date: Mon, 1 May 2006
Daniel Nogradi wrote:
'The source distribution of the 1.1.4 version comes with a Scripts directory where you can find player.py, gifmaker.py and explode.py which all deal with animated 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()
关于python tkinter 使用 PIL 显示动画 GIF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7960600/