1

So I have a gif and I need help animating it and putting in a loop. I can get the first frame to run but I can't get the next couple of frames to work. FYI the gif has like 51 frames.

import tkinter as tk

window = tk.Tk()
#make label for main page
windowmaintext = tk.Label(window, text="Welcome, to the Supercar Maintenance Calculator")
windowmaintext.grid(column = 1, row = 1)    

#make label for main page
windowmaintext2 = tk.Label(window, text="Which super car would you like to explore?")
windowmaintext2.grid(column = 1, row = 2)   

#make button to explore AMG cars
start = tk.Button(text= "Mercedes Benz AMG",fg = 'Blue')
start.grid (column = 1, row = 3)

#make button to explore audi cars
start = tk.Button(text= "Audi R8",fg = 'Red')
start.grid (column = 1, row = 4)

#make button to explore Lamborhini cars
start = tk.Button(text= "Lamborghini Huracan",fg = 'Gold')
start.grid (column = 1, row = 5)

#make button to explore Mclaren 720s cars
start = tk.Button(text= "Mclaren 720s",fg = 'Purple')
start.grid (column = 1, row = 6)

#name the window
window.title("Supercar Maintenance Calculator")

#open gif
logo = tk.PhotoImage(file="giphy.gif")
w = tk.Label(window,image=logo).grid(column = 1, row = 7)

#window size
window.geometry("600x600")

#end of page
window.mainloop()
Darsh Patel
  • 49
  • 1
  • 10

1 Answers1

1

An animated GIF contains a number of frames and you have to read each frame into a PhotoImage. Then you have to play them back explicitly. Tkinter can't read the delay time between frames so you'll have to test different values. See example below:

import tkinter as tk

root = tk.Tk()

framelist = []      # List to hold all the frames
frame_index = 0     # Frame index

while True:
    try:
        # Read a frame from GIF file
        part = 'gif -index {}'.format(frame_index)
        frame = tk.PhotoImage(file='images/animated.gif', format=part)
    except:
        last_frame = frame_index - 1    # Save index for last frame
        break               # Will break when GIF index is reached
    framelist.append(frame)
    frame_index += 1        # Next frame index

def animate(frame_number):
    if frame_number > last_frame:
        frame_number = 0
    label.config(image=framelist[frame_number]) 
    root.after(50, animate, frame_number+1)

label = tk.Label(root, bg='#202020')
label.pack()

animate(0)  # Start animation

root.mainloop()
figbeam
  • 7,001
  • 2
  • 12
  • 18