如何同时在tkinter画布上更改和移动图像?

时间:2019-01-08 19:40:26

标签: python tkinter tkinter-canvas

the looks of funktion 我正在编写一个将动画显示为动画书的代码。

因此,此代码必须更改图像并同时移动坐标。我写了代码。但是有时动画会滞后。

我拍了一段动画视频,然后发现了问题所在。

在我的代码中,程序首先更改坐标,然后更改图片。 实际上,此代码几乎没有问题,但是有时会滞后,然后只会移动图片。一段时间后,它将改变图片。 因此,我想我必须使用某种可以更改图像并同时移动图像的功能。 有什么办法可以实现?

这是我的代码

import tkinter as tk

class App(object):

    def GUI(self):

        root=tk.Tk()
        root.geometry("600x600")

        self.pic001=tk.PhotoImage(file="picture001.png")
        self.pic002=tk.PhotoImage(file="picture002.png")

        self.canvas = tk.Canvas(bg="black", width=796, height=816)
        self.canvas.place(x=0, y=0)

        self.item=self.canvas.create_image(0, 0, image=self.pic001, anchor=tk.NW)

        self.canvas.move(self.item,-51,10)
        self.canvas.itemconfig(self.item, image = self.pic002)    

        root.mainloop()

app=App()

app.GUI()

1 个答案:

答案 0 :(得分:0)

这是一个简单的动画脚本。

我绘制了6张图像,然后复制了5张图像以进行反向弹跳。

我每次都绘制一个新图像,而不是移动图像。

import tkinter as tk
from os import walk


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.geometry("600x300")
        self.image_names = []
        self.index_tracker = 0
        self.location = 1
        self.canvas = tk.Canvas(self, width=2000)
        self.canvas.pack()
        for(dirpath, dirnames, filenames) in walk('./Flip/'):
            for name in filenames:
                self.image_names.append(tk.PhotoImage(file="{}{}".format(dirpath, name)))

        tk.Button(self, text='Start animation!', command=self.start_animation).pack()

    def start_animation(self):
        if self.location < 80:
            self.canvas.delete('all')
            if self.index_tracker < len(self.image_names):
                self.canvas.create_image(self.location * 10, 75, image=self.image_names[self.index_tracker])
                self.location += 1
                self.index_tracker += 1
                self.after(100, self.start_animation)
            else:
                self.index_tracker = 0
                self.start_animation()


if __name__ == "__main__":
    App().mainloop()

您可以在我的Github here上获取此动画的图像文件。

结果:

enter image description here

相关问题