这是代码,真的显示了gif,但是很丑......我试图使用PIL,但是同样的bug。按照2个代码(我自己的第一个,网络的第2个)和打印:
gif文件(是一个随机文件要测试,这么可爱吧?kk):
请看截图了解:
第一个代码:
import tkinter as tk
from tkinter import Canvas, PhotoImage
x = 0
def animate(self):
global x
if x == 32:
x = 0
else:
self.pic["format"] = "gif -index " + str(x)
self.label1["image"] = self.pic
x += 1
print(x)
self.after(50, lambda: animate(self))
class run(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.pic = PhotoImage(file="/home/arnaldo/Desktop/b.gif", format = "gif -index 0")
self.label1 = tk.Label(width=350, height=233)
self.label1.pack(expand="yes", fill="both")
animate(self)
run().mainloop()
我在网上找到的第二个代码:
from tkinter import *
from PIL import Image, ImageTk
class MyLabel(Label):
def __init__(self, master, filename):
im = Image.open(filename)
seq = []
try:
while 1:
seq.append(im.copy())
im.seek(len(seq)) # skip to next frame
except EOFError:
pass # we're done
try:
self.delay = im.info['duration']
except KeyError:
self.delay = 100
first = seq[0].convert('RGBA')
self.frames = [ImageTk.PhotoImage(first)]
Label.__init__(self, master, image=self.frames[0])
temp = seq[0]
for image in seq[1:]:
temp.paste(image)
frame = temp.convert('RGBA')
self.frames.append(ImageTk.PhotoImage(frame))
self.idx = 0
self.cancel = self.after(self.delay, self.play)
def play(self):
self.config(image=self.frames[self.idx])
self.idx += 1
if self.idx == len(self.frames):
self.idx = 0
self.cancel = self.after(self.delay, self.play)
root = Tk()
anim = MyLabel(root, '/home/arnaldo/Desktop/a.gif')
anim.pack()
def stop_it():
anim.after_cancel(anim.cancel)
Button(root, text='stop', command=stop_it).pack()
root.mainloop()
两个都是丑陋的GIF ......