2013-04-01 253 views
2

我有我創建使用PIL,然後加入到使用TKinter畫布光象。圖像顯示正常。但是,我無法使PIL旋轉功能正常工作。這裏是我的代碼:Python的Tkinter的旋轉圖像動畫

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

但是,在這種情況下圖像不顯示。我希望能夠對圖像的旋轉進行動畫製作,但我甚至無法旋轉工作!任何建議,非常感謝。

編輯:校正,它已經被添加到屏幕

回答

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

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

我花了一段時間來得到這個工作,所以我想我會分享。