python读取gif图片并显示,python tkinter使用PIL显示动画GIF

Is there any way to display an animated GIF in Tkinter using Python Image Library?

I thought the ImageSequence module would be the way to do it, but I don't know how to use it and if it's possible.

The first question is if there is any easy way. For example: load a GIF using PIL and the ImageSequence and just draw it on a Tkinter window using ImageTk.PhotoImage and it will be animated.

Or do I have to set up a function myself, using the after method or something like time.sleep to loop through the GIF frames and draw them on a tkinter window?

The second question: even if I have to make a function to loop through the GIF frames, is the ImageSequence module supposed to do this or PIL has another module for it?

I'm using Python 3.1 and a private port of PIL, indicated in this 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.'

they're still shipped with 1.1.5 (and 1.1.6), and they should work.

if all you're missing is a few files from the script directory, you can get

them here:

player.py is run from the command line

see if this one works for you:

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值