Viewing an Animated GIF with Python

Animated GIFs are a fun way to share silent videos on social media. This website has a tutorial to help you learn how to create your own animated GIFs with Python. But what if you wanted to view an animated GIF with Python?

If you’re wondering if Python can present an animated GIF to the viewer, then you’ve found the right tutorial!

You will learn how to display a GIF with Python using the following methods:

  • Using tkinter to view an animated GIF
  • Using PySimpleGUI to view an animated GIF
  • Using Jupyter Notebook to view an animated GIF

Getting Started

The first step is to find an animated GIF you’d like to display. You can get GIFs from Google or Giphy. There are also many applications that you can use to make your own GIFs.

For the purposes of this tutorial, you can use this silly example GIF that shows a “hello world” example from Asciimatics, a Python TUI package:

Asciimatics hello world GIF

Save this file as asicmatics_hello.gif to your computer so you can use it in the examples in this tutorial.

Now that you have an animated GIF, you are ready to learn how to display it using Python!

Viewing the Animated GIF with tkinter

StackOverflow has many suggestions you can use to view animated GIFs with Python. One suggestion was to use tkinter, the Python GUI toolkit included with Python, to view an animated GIF.

The following code is a cleaned up variation on the suggestion from that post:

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)

class Main():
    def __init__(self):
        root = Tk()
        self.anim = MyLabel(root, 'asciimatics_hello.gif')
        self.anim.pack()
        Button(root, text='stop', command=self.stop_it).pack()
        root.mainloop()

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


main = Main()

This code will import tkinter and create a Label() widget. The label can contain all kinds of different things, including images. For this example, you will create a list of frames from the GIF and store them in self.frames as instances of ImageTk.PhotoImage.

Then you will call tkinter’s handy after() method to make it play the frames back after a short delay. You use this command to call play() recursively.

When you run this code, you should see the following:

You’ll note that in Tkinter, it seems to default to playing the GIF in black-and-white. You can do some more searching yourself and see if you can find a way to make it display the GIF in color.

Now, let’s try viewing it with PySimpleGUI!

Viewing the Animated GIF with PySimpleGUI

Tkinter isn’t the only GUI toolkit in town. You can also use PySimpleGUI, a wrapper around Tkinter, wxPython, and PyQt. If you’d like to know more, you can check out this brief intro PySimpleGUI.

You will need to install PySimpleGUI since it doesn’t come with Python. You can use pip to do that:

python -m pip install pysimplegui

Now you’re ready to write some code. The following code is based on an example from the PySimpleGUI GitHub page:

import PySimpleGUI as sg
from PIL import Image, ImageTk, ImageSequence

gif_filename = 'asciimatics_hello.gif'

layout = [[sg.Image(key='-IMAGE-')]]

window = sg.Window('Window Title', layout, element_justification='c', margins=(0,0), element_padding=(0,0), finalize=True)

interframe_duration = Image.open(gif_filename).info['duration']

while True:
    for frame in ImageSequence.Iterator(Image.open(gif_filename)):
        event, values = window.read(timeout=interframe_duration)
        if event == sg.WIN_CLOSED:
            exit(0)
        window['-IMAGE-'].update(data=ImageTk.PhotoImage(frame) )

This code is a little shorter than the Tkinter example, so that’s pretty neat. Give it a try and see what happens!

Now you’re ready to try out viewing a GIF in Jupyter Notebook!

Viewing the Animated GIF in Jupyter Notebook

Jupyter Notebooks are great ways to share code along with some markup. You can create presentations, code examples, and their output and even widgets using Jupyter.

You can also insert images into Jupyter Notebook cells. That includes animated GIFs too! If you’d like to learn more about Jupyter Notebook, you should check out this introductory tutorial.

You’ll need to install Jupyter to be able to follow along with this part of the tutorial. Fortunately, that’s only a pip-install away:

python -m pip install jupyter

Now that you have Jupyter Notebook installed, open up your terminal or Powershell and run the following command:

jupyter notebook

The next step is to create a new Notebook. Click the New button on the top right in the new web page that should have loaded in your default browser. Look for a URL like this: http://localhost:8888/tree

You will be presented with several choices when you click the New button. You should pick the top choice, which is Notebook. A new browser tab will open, and you may see a pop-up window asking which Kernel to choose. The default will probably be Python 3, which is what you want. Pick that, and you should be good to go!

In the middle of the toolbar along the top of the Jupyter Notebook Window, you will see a drop-down labeled Code. Click on that and change it to Markdown. Now the current cell is n Markdown mode instead of Code mode. That’s great!

Enter the following into your cell:

![MyGif](asciimatics_hello.gif "segment")

Make sure that asciimatics_hello.gif is in the same folder as your new Jupyter Notebook is in. Or you can put the absolute path to the file in there instead.

Now, you need to run the cell to see the animated GIF. You can click the play button in the toolbar or press SHIFT+ENTER. Either way that should run the cell.

At this point, you should see the following:

You did it! That looks great!

Wrapping Up

Python has many different ways to view animated GIFs. You can use the built-in Tkinter GUI package, the PySimpleGUI package, or Jupyter Notebook.

There are probably others you can use as well. Feel free to drop a comment and let us all know what version you like best or a different package that you’ve tried.