如何使gif始终在python中循环?

时间:2018-12-30 16:42:16

标签: python loops

这是我的代码:

from PIL import Image, ImageSequence
import os

class MyImage:
    def __init__(self,file_path):
        self.image = Image.open(file_path)

def get_rewind(self):
    iter = ImageSequence.Iterator(self.image)
    index = 1
    for frame in iter:

        print("image [{}] : mode {}, size {}".format(index,frame.mode,frame.size))
        frame.save("./rewind-result/frame{}.png".format(index))
        index += 1

    sequence = []

    for f in ImageSequence.Iterator(self.image):
        sequence.append(f.copy())

    sequence.reverse()
    sequence[0].save("./reverse_out.gif",save_all=True, append_images=sequence[1:])

if __name__ == '__main__':
    image = MyImage("./test.gif")
    image.get_rewind()

gif是reverse_out.gif,但它循环了一次。那么如何设置循环的属性呢?(不是由photoshop来完成的)

1 个答案:

答案 0 :(得分:0)

一种不健康的方法:

from tkinter import *

class GIF(Tk):
    def __init__(self):
        super().__init__()
        self.geometry("500x500")
        self.x = 0

        self.img = PhotoImage(file="filename.gif", format=f"gif -index {self.x}")

        self.canvas = Canvas(self,width=1366, height=768,bd=0,highlightthickness=0)
        self.canvas.pack(expand = 1, fill = BOTH)

        self._img = self.canvas.create_image(0, 0, image=self.img,anchor = NW)
        self.run_gif()
        self.mainloop()

    def run_gif(self):
        try:
            self.img = PhotoImage(file="filename.gif", format=f"gif -index {self.x}")
            self.canvas.itemconfigure(self._img, image=self.img)
            self.x += 1
        except:
            self.x = 0

        self.canvas.after(10, self.run_gif)

GIF()

但是有些人很健康!