3

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

但是,在这种情况下,图像只是不显示。我希望能够为图像的旋转设置动画,但我什至根本无法进行旋转!非常感谢任何建议。

编辑:更正,旋转已添加到屏幕后将不起作用

4

2 回答 2

12

这是一个使用 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 版本,请参阅修订历史

于 2013-04-01T02:41:56.220 回答
5

这是上面 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()

我花了一段时间才让这个工作,所以我想我会分享。

于 2016-06-01T19:27:58.197 回答