Python Tkinter旋转图像动画

时间:2013-04-01 01:36:29

标签: python animation rotation tkinter python-imaging-library

我有一个使用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()

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

编辑:更正,旋转将在已经添加到屏幕后无效

2 个答案:

答案 0 :(得分:8)

以下是使用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

答案 1 :(得分:2)

以上是unutbu的答案,但在Python 3中:

import time
import tkinter
from PIL import Image, ImageTk

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

        self.process_next_frame = self.draw().__next__  # Using "next(self.draw())" doesn't work
        master.after(1, self.process_next_frame)

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

root = tkinter.Tk()
app = SimpleApp(root, 'images.png')
root.mainloop()

我花了一段时间才开始工作,所以我想我会分享。