Skip to main content
 首页 » 编程设计

python之Tkinter:在没有 PIL 的情况下在 Canvas 上移动 Gif

2024年09月07日9EasonJim

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

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("/image/57uJJ.gif", "13.gif") 
    url.urlretrieve("/image/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 

返回 True 然后 .png 文件也被支持而无需额外的库。