Tkinter:在没有 PIL 的 canvas 上移动 Gif

Tkinter: Moving a Gif on a canvas without PIL

我在 python 3 的 tkinter 中遇到问题。我想在 python、tkinter 中创建动画游戏角色而不使用 PIL。我找到了一种使用 gif 动画角色的方法,但我不知道如何移动我尝试使用的 gif canvas.move 这是我的代码:

from tkinter import *
import os
import time
root = Tk()
c = Canvas(root,width = 500,height = 500)
c.pack()
frames = [PhotoImage(file=(os.path.expanduser("~/Desktop/DaQueenIDLE.gif")),format = 'gif -index %i' % (i)) for i in range(2)]
def update(ind):
    frame = frames[ind]
    ind += 1
    if ind >= 2:
        ind = 0
    label.configure(image=frame)
    root.after(100, update, ind)
label = Label(root)
label.pack()
root.after(0, update, 0)
c.move(frames,0,-100)
root.update()
root.mainloop()

move 是 Canvas 的方法,它的第一个参数需要是 Canvas.

上的一个项目

在你的情况下 frames 不是 Canvas 上的项目。

替换:

def update(ind):
    #...
    label.configure(image=frame)
    root.after(100, update, ind)
label = Label(root)
label.pack()

与:

def update(ind):
    #...
    c.itemconfig(character, image=frame)
    c.move(character, 1, 1)
    root.after(100, update, ind)
character = c.create_image((47,47), image=frames[0])

将您的标签转换为 Canvas 中的图像项并移动它。

例子

下面是一个完整的例子下载(你可以在初始运行之后评论download_images).gif图片如下在线:

然后在两者之间制作动画时移动图像:

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def download_images():
    # In order to fetch the image online
    try:
        import urllib.request as url
    except ImportError:
        import urllib as url
    url.urlretrieve("https://i.stack.imgur.com/57uJJ.gif", "13.gif")
    url.urlretrieve("https://i.stack.imgur.com/8LThi.gif", "8.gif")


def animate_and_move(i):
    i = (i + 1) % 2
    canvas.itemconfig(moving_image, image=canvas.images[i])
    canvas.move(moving_image, 1, 1)
    canvas.after(100, animate_and_move, i)


if __name__ == '__main__':
    download_images() # comment out after initial run
    root = tk.Tk()
    canvas = tk.Canvas(root, height=644, width=644, bg='#ffffff')
    canvas.images = list()
    canvas.images.append(tk.PhotoImage(file="8.gif"))
    canvas.images.append(tk.PhotoImage(file="13.gif"))
    moving_image = canvas.create_image((164, 164), image=canvas.images[0])
    animate_and_move(0)
    canvas.pack()
    root.mainloop()

注意如果:

import tkinter
tkinter.TkVersion >= 8.6

returns True 然后 .png 文件也支持,无需额外的库。