Python的Tkinter的旋转图像动画(Python Tkinter rotate image

2019-08-18 11:51发布

我有我创建使用PIL,然后加入到使用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()

然而,图像只是没有在这种情况下出现。 我希望能够以动画图像的旋转,但我甚至不能旋转在所有的工作! 任何建议都非常赞赏。

编辑:校正,它已经被添加到屏幕后的旋转将无法正常工作

Answer 1:

这里是使用旋转的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版本,请参见修订历史记录 。



Answer 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()

我花了一段时间来得到这个工作,所以我想我会分享。



文章来源: Python Tkinter rotate image animation