python tkinter使用PIL显示动画GIF

2024-04-20 14:14:28 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有什么方法可以使用Python图像库在Tkinter中显示动画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中指明。


Tags: 模块方法函数图像piltimetkinter绘制
2条回答

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()

简单PIL版本:

canvas = Image.new("RGB",(Width,Height),"white")
gif = Image.open('text.gif', 'r')
frames = []
try:
    while 1:
        frames.append(gif.copy())
        gif.seek(len(frames))
except EOFError:
    pass

for frame in frames:
     canvas.paste(frame)
     canvas.show()

相关问题 更多 >