Python tkinter displays animated GIF using PIL

Is there a way to display an animated GIF in Tkinter using a Python image library?

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

First question: is there any simple way. For example: upload a GIF using PIL and ImageSequence and just draw it in the Tkinter window using ImageTk.PhotoImage and it will be animated.

Or do I need to configure the function myself using the after method or something like time.sleep to loop through GIF frames and draw them in the tkinter window?

Second question: even if I need to make a function for looping through GIF frames, should the ImageSequence module be used or does PIL have another module for it?

I am using Python 3.1 and the private PIL port specified in this thread .

+4
source share
1 answer

Newsgroups: comp.lang.python

From: "Fredrik Lundh"

Date: Monday May 1, 2006

Daniel Nogrady wrote:

'The original distribution of version 1.1.4 comes with scripts where you can find player.py, gifmaker.py and explode.py that deal with animated gifs. ''

they still come with 1.1.5 (and 1.1.6) and they should work.

If all you are missing is a few files from the script directory, you can get them here:

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


player.py is launched from the command line

see if this 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() 
+6
source

Source: https://habr.com/ru/post/1379041/


All Articles