1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| from tkinter import *
from PIL import Image, ImageTk
from itertools import count, cycle
class ImageLabel(Label):
def load(self, img, im):
if isinstance(im, str):
im = Image.open(im)
frames = []
img = img
try:
for i in count(1):
frames.append(ImageTk.PhotoImage(im.copy()))
im.seek(i)
except EOFError:
pass
self.frames = cycle(frames)
try:
self.delay = im.info['duration']
except:
self.delay = 100
if len(frames) == 1:
img.itemconfig(img, image=next(self.frames))
else:
self.next_frame(img)
def unload(self):
img.itemconfig(image=None)
self.frames = None
def next_frame(self, img):
if self.frames:
c.itemconfig(img, image=next(self.frames))
self.after(self.delay, self.next_frame)
#demo :
root = Tk()
c = Canvas(root)
c.pack()
chat_img = PhotoImage(file='images/chat.gif')
chat = c.create_image(0, 0, image=chat_img)
lbl = ImageLabel(c)
lbl.pack()
lbl.load(chat, 'images/chat.gif')
root.mainloop() |
Partager