-1
from tkinter import *
import time
import os
root = Tk()

frameCnt = 12
frames = [PhotoImage(file='mygif.gif',format = 'gif -index %i' %(i)) for i in range(frameCnt)]

def update(ind):

    frame = frames[ind]
    ind += 1
    if ind == frameCnt:
        ind = 0
    label.configure(image=frame)
    root.after(100, update, ind)
label = Label(root)
label.pack()
root.after(0, update, 0)
root.mainloop()

I want to run file gif one time when i opened window . this code run gif infinity.

2 Answers2

1

If you want to animate the GIF only once, you don't need to reset the index as said by Bryan's comment.

Hard-coded frameCnt is not flexible because it need to be changed if another GIF image is used.

Also using tkinter.PhotoImage() to load frames from a GIF image is a bit slow when comparing with Pillow module, so I would suggest to use Pillow module.

import tkinter as tk
from PIL import Image, ImageTk, ImageSequence

root = tk.Tk()

label = tk.Label(root)
label.pack()

im = Image.open('mygif.gif')
frames = [ImageTk.PhotoImage(frame) for frame in ImageSequence.Iterator(im)]

def update(idx=0):
    if idx < len(frames):
        label.configure(image=frames[idx])
        root.after(100, update, idx+1)

update() # start the animation
root.mainloop()
acw1668
  • 40,144
  • 5
  • 22
  • 34
0

As Bryan Oakley commented, we're already checking the count, so we just exit the function.

from tkinter import *
import time
import os
root = Tk()

frameCnt = 12
frames = [PhotoImage(file='mygif.gif',format = 'gif -index %i' %(i)) for i in range(frameCnt)]

def update(ind):
    frame = frames[ind]
    ind += 1
    label.configure(image=frame)
    if ind == frameCnt:
        return
    root.after(500, update, ind)
label = Label(root)
label.pack()
root.after(0, update, 0)
root.mainloop()
kimhyunju
  • 309
  • 1
  • 7