Tkinter GIFS

There is no built in facility for dealing with animated gifs in TKinter but with a little effort it is quite easy to create something that works.   This python class provides an easy way to include animated gifs on a TKinter canvas.

https://byteinsight.co.uk/wp-content/uploads/2019/03/animatedGif.py_.zip

STEP 1 – SETUP

To use this class you must download the animatedGif.py, unzip it and place it in the same folder as your main program file.  Lastly you must include it in your program.

from animatedGif import AnimatedGif

STEP 2 – CREATE AN ANIMATEDGIF OBJECT.

This step create a new animated gif object that you can work with in your game.  This example assumes that there is a player1 gif image located inside an images folder inside the program folder.

player1 = AnimatedGif('./images/player1.gif')

OPTION 1 – GET THE CURRENT FRAME.

If you just want to display the current frame on the canvas then you must use the currentFrame method.  The following example adds the current frame to the canvas object at position (200px,200px).

player1Image = canvas.create_image(200,200,image=player1.currentFrame())

OPTION 2 – GET THE NEXT FRAME

You will almost certainly want to animate your gif image which requires the nextFrame method.   The following method updates the canvas image and then tells the program to update it again in 60 milliseconds.

def updateDisplay(self):
canvas.itemconfig(player1Image, image = player1.nextFrame())
canvas.update()
root.after(60,updateDisplay)

There is also an info method which can be used to provide information on the animatedGif loaded in step 1 that can be used for debugging purposes.

CREDITS:

The code has been taken/developed from the many questions on this topic that are circulating on the web including:

2 Comments on “Tkinter GIFS

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.