Saturday, May 18, 2024
HomePythonViewing an Animated GIF with Python

Viewing an Animated GIF with Python


Animated GIFs are a enjoyable strategy to share silent movies on social media. This web site has a tutorial that can assist you study how you can create your personal animated GIFs with Python. However what in case you needed to view an animated GIF with Python?

In the event you’re questioning if Python can current an animated GIF to the viewer, then you definitely’ve discovered the best tutorial!

You’ll learn to show a GIF with Python utilizing the next strategies:

  • Utilizing tkinter to view an animated GIF
  • Utilizing PySimpleGUI to view an animated GIF
  • Utilizing Jupyter Pocket book to view an animated GIF

Getting Began

Step one is to seek out an animated GIF you’d prefer to show. You will get GIFs from Google or Giphy. There are additionally many functions that you need to use to make your personal GIFs.

For the needs of this tutorial, you need to use this foolish instance GIF that exhibits a “howdy world” instance from Asciimatics, a Python TUI package deal:

Save this file as asicmatics_hello.gif to your pc so you need to use it within the examples on this tutorial.

Now that you’ve got an animated GIF, you’re able to learn to show it utilizing Python!

Viewing the Animated GIF with tkinter

StackOverflow has many strategies you need to use to view animated GIFs with Python. One suggestion was to make use of tkinter, the Python GUI toolkit included with Python, to view an animated GIF.

The next code is a cleaned up variation on the suggestion from that publish:

from tkinter import *
from PIL import Picture, ImageTk

class MyLabel(Label):
    def __init__(self, grasp, filename):
        im = Picture.open(filename)
        seq =  []
        strive:
            whereas 1:
                seq.append(im.copy())
                im.search(len(seq)) # skip to subsequent body
        besides EOFError:
            cross # we're completed

        strive:
            self.delay = im.information['duration']
        besides KeyError:
            self.delay = 100

        first = seq[0].convert('RGBA')
        self.frames = [ImageTk.PhotoImage(first)]

        Label.__init__(self, grasp, picture=self.frames[0])

        temp = seq[0]
        for picture in seq[1:]:
            temp.paste(picture)
            body = temp.convert('RGBA')
            self.frames.append(ImageTk.PhotoImage(body))

        self.idx = 0

        self.cancel = self.after(self.delay, self.play)

    def play(self):
        self.config(picture=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 Principal():
    def __init__(self):
        root = Tk()
        self.anim = MyLabel(root, 'asciimatics_hello.gif')
        self.anim.pack()
        Button(root, textual content="cease", command=self.stop_it).pack()
        root.mainloop()

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


most important = Principal()

This code will import tkinter and create a Label() widget. The label can include every kind of various issues, together with pictures. For this instance, you’ll create an inventory of frames from the GIF and retailer them in self.frames as cases of ImageTk.PhotoImage.

Then you’ll name tkinter’s useful after() methodology to make it play the frames again after a brief delay. You utilize this command to name play() recursively.

Once you run this code, you must see the next:

You’ll observe that in Tkinter, it appears to default to enjoying the GIF in black-and-white. You are able to do some extra looking out your self and see if you could find a strategy to make it show the GIF in coloration.

Now, let’s strive viewing it with PySimpleGUI!

Viewing the Animated GIF with PySimpleGUI

Tkinter isn’t the one GUI toolkit on the town. You can too use PySimpleGUI, a wrapper round Tkinter, wxPython, and PyQt. In the event you’d prefer to know extra, you’ll be able to take a look at this temporary intro PySimpleGUI.

You’ll need to put in PySimpleGUI because it doesn’t include Python. You should use pip to try this:

python -m pip set up pysimplegui

Now you’re prepared to write down some code. The next code is predicated on an instance from the PySimpleGUI GitHub web page:

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

gif_filename="asciimatics_hello.gif"

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

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

interframe_duration = Picture.open(gif_filename).information['duration']

whereas True:
    for body in ImageSequence.Iterator(Picture.open(gif_filename)):
        occasion, values = window.learn(timeout=interframe_duration)
        if occasion == sg.WIN_CLOSED:
            exit(0)
        window['-IMAGE-'].replace(knowledge=ImageTk.PhotoImage(body) )

This code is a bit of shorter than the Tkinter instance, in order that’s fairly neat. Give it a attempt to see what occurs!

Now you’re able to check out viewing a GIF in Jupyter Pocket book!

Viewing the Animated GIF in Jupyter Pocket book

Jupyter Notebooks are nice methods to share code together with some markup. You may create shows, code examples, and their output and even widgets utilizing Jupyter.

You can too insert pictures into Jupyter Pocket book cells. That features animated GIFs too! In the event you’d prefer to study extra about Jupyter Pocket book, you must take a look at this introductory tutorial.

You’ll want to put in Jupyter to have the ability to observe together with this a part of the tutorial. Happily, that’s solely a pip-install away:

python -m pip set up jupyter

Now that you’ve got Jupyter Pocket book put in, open up your terminal or Powershell and run the next command:

jupyter pocket book

The following step is to create a brand new Pocket book. Click on the New button on the highest proper within the new internet web page that ought to have loaded in your default browser. Search for a URL like this: http://localhost:8888/tree

You may be offered with a number of selections if you click on the New button. You must decide the best choice, which is Pocket book. A brand new browser tab will open, and you might even see a pop-up window asking which Kernel to decide on. The default will most likely be Python 3, which is what you need. Choose that, and try to be good to go!

In the course of the toolbar alongside the highest of the Jupyter Pocket book Window, you will notice a drop-down labeled Code. Click on on that and alter it to Markdown. Now the present cell is n Markdown mode as a substitute of Code mode. That’s nice!

Enter the next into your cell:

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

Be sure that asciimatics_hello.gif is in the identical folder as your new Jupyter Pocket book is in. Or you’ll be able to put absolutely the path to the file in there as a substitute.

Now, you must run the cell to see the animated GIF. You may click on the play button within the toolbar or press SHIFT+ENTER. Both manner that ought to run the cell.

At this level, you must see the next:

You probably did it! That appears nice!

Wrapping Up

Python has many alternative methods to view animated GIFs. You should use the built-in Tkinter GUI package deal, the PySimpleGUI package deal, or Jupyter Pocket book.

There are most likely others you need to use as effectively. Be happy to drop a remark and allow us to all know what model you want greatest or a unique package deal that you just’ve tried.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments