2
\$\begingroup\$

Recently, I made this gif opener using tkinter:

import tkinter as tk
from tkinter import filedialog as fd
import time
import threading

def getfile():
     file = fd.askopenfilename()
     window = tk.Toplevel()
     def run_gif():
          i = 0
          while True:
               try:
                    photo = tk.PhotoImage(file = file,format="gif -index" +' '+ str(i))
                    gif = tk.Label(window, image=photo)
                    gif.grid(row=0,column=0)
                    i += 1
                    time.sleep(0.0001)
               except:
                    i = 0
     gif_thread=threading.Thread(target=run_gif)
     gif_thread.start()
     window.mainloop()
          
          
def display():
     root = tk.Tk()
     root.title(".gif opener")
     root.geometry('50x100')
     root.configure(bg = "lightgreen")
     label = tk.Label(root, text = ".gif opener")
     label.pack()
     button = tk.Button(root, text = "File", command = getfile)
     button.place(x = "50", y= "50")
     root.mainloop()

display()

However, every time I open a gif, the animation is really laggy.

Is there any way to make the gifs flow smoother? Any help will be appreciated.

\$\endgroup\$
1
  • \$\begingroup\$ Why is there a sleep()? \$\endgroup\$ Commented May 17, 2021 at 16:39

1 Answer 1

1
\$\begingroup\$

Your problem may be similar to this one:

https://stackoverflow.com/questions/50904093/gif-animation-in-tkinter-with-pill-flickering-on-every-other-frame

I tried your code on gif which has a 2nd disposal method. Works, but loops over frames too quickly. GIFs with the 1st disposal method fail.

Also pay attention to the frame delay/frame rate. Different GIFs can have different values. You can use third party libraries like Pillow to get file information.


from PIL import Image

f = Image.open("tenor.gif")
print(f.info) # duration in ms
print(f.disposal_method)
print(f.n_frames) # number of frames

Output example:

{'version': b'GIF89a', 'background': 140, 'transparency': 140, 'duration': 160, 'extension': (b'NETSCAPE2.0', 795), 'loop': 0}
2
12

You can use some custom label classes. https://stackoverflow.com/a/43770948/8349697

Consider using the PyQt5 library. I tried some test gifs with QtWidgets, and it works much better than tkinter. PyQt can display animated gifs using QMovie.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.