here2share

# Tk_animate_gif.py

Sep 10th, 2020 (edited)
429
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.71 KB | None | 0 0
  1. # Tk_animate_gif.py # https://media.giphy.com/media/UuYo0xOTHOvTDEkRdv/giphy.gif
  2.  
  3. from Tkinter import *
  4. from PIL import Image, ImageTk
  5. from tkFileDialog import askopenfilename
  6. import time
  7. import os
  8. root = Tk()
  9.  
  10. xx = 600
  11. yy = 600
  12. canvas = Canvas(root, width=xx, height=yy)
  13. canvas.grid()
  14.  
  15. filename = askopenfilename(filetypes=[('gif files', '.gif')]) # needs to be placed after pack()
  16.  
  17. img_data = Image.open(filename)
  18. # print list(img_data.getdata().convert('RGB')) # ... or RGBA
  19.  
  20. ww,hh = img_data.size
  21. img = Image.new("RGB",(ww,hh))
  22. seq = []
  23.  
  24. label = Label(root, image=None)
  25. label.grid(row=0, column=0)
  26.  
  27. try:
  28.     while 1:
  29.         seq.append(img_data.copy())
  30.         img_data.seek(len(seq)) # skip to next frame
  31. except EOFError:
  32.     pass # task done
  33.  
  34. L = len(seq)
  35. print 'number of frames:',L
  36. try:
  37.     delay = img_data.info['duration']
  38. except KeyError:
  39.     delay = 100
  40. print 'ms delay:',delay
  41.  
  42. frames = []
  43. for image in seq:
  44.     frame = image.convert('RGBA')
  45.     frames.append(ImageTk.PhotoImage(frame))
  46.  
  47. def play(i):
  48.     label.configure(image=frames[i])
  49.     label.update()
  50.     i += 1
  51.     if i == L:
  52.         i = 0
  53.     root.after(delay, play, i)
  54. root.after(0, play, 0)
  55. root.mainloop()
  56.  
  57. # canvas.delete('gif'+str(p)) will most likely cause too much flickering...
  58. # ... or without... might significantly keep reducing the process speed
  59. '''
  60. L = len(frames)
  61. buffer = 0
  62. while 1:
  63.     if time.time() > ta:
  64.         ta = time.time()+1.5
  65.         p = buffer
  66.         buffer = (1,0)[buffer]
  67.         canvas.create_image(1, 1, anchor=NW, image=frames[i%L], tag='gif'+str(buffer))
  68.         canvas.delete('gif'+str(p))
  69.     i = (i+1)%L
  70.     canvas.create_image(1, 1, anchor=NW, image=frames[i%L], tag='gif'+str(buffer))
  71.     canvas.update()
  72.     while time.time() < tb:
  73.         pass
  74.     tb = time.time()+0.01
  75. '''
Add Comment
Please, Sign In to add comment