Tkinter-Python在按下按钮时旋转图像动画

时间:2020-06-20 01:33:27

标签: python image button tkinter rotation

我正在尝试在按下按钮的同时对图像进行动画处理,否则图像将停止

import time
import tkinter
from PIL import Image, ImageTk
from gpiozero import Button
import RPi.GPIO as GPIO
sensor = Button(11)

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__  
        master.after(1, self.process_next_frame)

    def draw(self):

        image = Image.open(self.filename)
        angle = 0
        print(self.process_next_frame)
        while (sensor.is_pressed):
            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, 'load.png')
root.mainloop() 

如果将while设置为True,图像将自动开始旋转,但是如果添加sensor.is_pressed,则图像不会出现。 另外,我尝试将angle +=1之前的那段时间移开,但是即使我按下按钮,图像也只会出现并且永远不会开始移动

1 个答案:

答案 0 :(得分:-1)

使用root.update方法强制更新UI

        angle += 1
        angle %= 360
        self.root.update()
        time.sleep(0.02)