gpt4 book ai didi

python - 使用 tkinter 在 python 中播放动画 GIF

转载 作者:行者123 更新时间:2023-11-28 21:05:35 25 4
gpt4 key购买 nike

我想使用 python3 和 tkinter 创建一个虚拟宠物风格的游戏。到目前为止,我有主窗口并开始放入标签,但我遇到的问题是播放动画 gif。我在这里搜索并找到了一些答案,但他们不断抛出错误。我找到的结果是使用 PhotoImage 的 gif 的索引位置在一定范围内继续。

    # Loop through the index of the animated gif
frame2 = [PhotoImage(file='images/ball-1.gif', format = 'gif -index %i' %i) for i in range(100)]

def update(ind):

frame = frame2[ind]
ind += 1
img.configure(image=frame)
ms.after(100, update, ind)

img = Label(ms)
img.place(x=250, y=250, anchor="center")

ms.after(0, update, 0)
ms.mainloop()

当我在终端中使用“pyhton3 main.py”运行它时,出现以下错误:

_tkinter.TclError: no image data for this index

我忽略或完全遗漏了什么?

这是查看完整项目的 GitHub 存储库链接:VirtPet_Python

提前致谢!

最佳答案

错误意味着您尝试加载 100 帧,但 gif 的帧数少于此数。

众所周知,tkinter 中的动画 gif 很糟糕。我很久以前写了这段代码,你可以从中窃取,但除了小 gif 之外,其他任何东西都会变得迟钝:

import tkinter as tk
from PIL import Image, ImageTk
from itertools import count

class ImageLabel(tk.Label):
"""a label that displays images, and plays them if they are gifs"""
def load(self, im):
if isinstance(im, str):
im = Image.open(im)
self.loc = 0
self.frames = []

try:
for i in count(1):
self.frames.append(ImageTk.PhotoImage(im.copy()))
im.seek(i)
except EOFError:
pass

try:
self.delay = im.info['duration']
except:
self.delay = 100

if len(self.frames) == 1:
self.config(image=self.frames[0])
else:
self.next_frame()

def unload(self):
self.config(image="")
self.frames = None

def next_frame(self):
if self.frames:
self.loc += 1
self.loc %= len(self.frames)
self.config(image=self.frames[self.loc])
self.after(self.delay, self.next_frame)

root = tk.Tk()
lbl = ImageLabel(root)
lbl.pack()
lbl.load('ball-1.gif')
root.mainloop()

关于python - 使用 tkinter 在 python 中播放动画 GIF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43770847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com