Python Tkinter旋转图像动画

我有一个使用PIL创建的PhotoImage,然后添加到TKinter画布中.图像显示正常.但是,我无法让PIL旋转功能正常工作.这是我的代码:

 #This works fine
 image = Image.open('img.png')
 canvas_image = ImageTk.PhotoImage(rotated_image)
 canvas_object = canvas.create_image(30+10*int(steps),250, image=canvas_image)
 canvas.pack()

 #this does not work
 canvas.delete(canvas_object)
 rotated_image = image.rotate(1)
 canvas_image = ImageTk.PhotoImage(rotated_image)
 canvas_object = canvas.create_image(30+10*int(steps),250, image=canvas_image)
 canvas.update()

但是,在这种情况下,图像不会显示.我希望能够为图像的旋转设置动画,但我甚至无法轮换工作!任何建议都非常感谢.

编辑:校正,旋转在已经添加到屏幕后不起作用

最佳答案
这是一个使用Python3旋转图像的示例:

import tkinter as tk
from PIL import ImageTk
from PIL import Image

class SimpleApp(object):
    def __init__(self, master, filename, **kwargs):
        self.master = master
        self.filename = filename
        self.canvas = tk.Canvas(master, width=500, height=500)
        self.canvas.pack()

        self.update = self.draw().__next__
        master.after(100, self.update)

    def draw(self):
        image = Image.open(self.filename)
        angle = 0
        while True:
            tkimage = ImageTk.PhotoImage(image.rotate(angle))
            canvas_obj = self.canvas.create_image(
                250, 250, image=tkimage)
            self.master.after_idle(self.update)
            yield
            self.canvas.delete(canvas_obj)
            angle += 10
            angle %= 360

root = tk.Tk()
app = SimpleApp(root, '/path/to/image.png')
root.mainloop()

有关Python2版本,请参阅revision history.

转载注明原文:Python Tkinter旋转图像动画 - 代码日志