Python Tkinter 旋转图像动画 [英] Python Tkinter rotate image animation
问题描述
我有一个使用 PIL 创建然后添加到 TKinter 画布的 PhotoImage.图像显示正常.但是,我无法让 PIL 旋转功能正常工作.这是我的代码:
I have a PhotoImage that I created using PIL and then added to a TKinter canvas. The image shows up fine. However, I can't get the PIL rotate function to work correctly. Here is my code:
#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()
但是,在这种情况下图像不会显示.我希望能够为图像的旋转设置动画,但我什至无法进行旋转工作!非常感谢任何建议.
However, the image just does not show up in this case. I want to be able to animate the rotation of an image, but I can't even get a rotation to work at all! Any suggestions are greatly appreciated.
更正,添加到屏幕后旋转将不起作用
correction, the rotation will not work after it's already been added to the screen
推荐答案
以下是使用 Python3 旋转图像的示例:
Here is an example which rotates an image using 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 版本,请参阅修订历史.
For a Python2 version, see the revision history.
这篇关于Python Tkinter 旋转图像动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!