Search code examples
pythontkinterpython-imaging-libraryloading

How to rotate a image in Python tkinter Window


I am working on a python messaging application using tkinter and i need a loading screen animation but none of them where fitting with my purpose so i Tried to rotate a image in python continusly which will look like a animation.

This is the image i want to ratate for some time in tkinter The application code i only need a simple tkinter window with the rotating screen

I tried google and i got this code to rote a image

from PIL import Image # Import Image class from the library.

image = Image.open("file.jpg") # Load the image.
rotated_image = image.rotate(180) # Rotate the image by 180 degrees.
rotated_image.save("file_rotated.jpg") 

So i tried using this code like this:-

from tkinter import *
from PIL import ImageTk, Image
import os

root = Tk()

c = Canvas(root, width=700, height=700)
c.pack()


while True:
    
    img = ImageTk.PhotoImage(Image.open(r"Loading_Icon.png"))
    c.create_image(100, 100, image=img, anchor=NW)
    
    image = Image.open(Loading_Icon.png") # Load the image.
    rotated_image = image.rotate(30)
     
    os.remove("Loading_Icon.png")
    rotated_image.save("Loding_Icon.png") 
    
    root.mainloop()
    c.delete("all")
    

Solution

  • Look at this:

    from PIL import Image, ImageTk
    import tkinter as tk
    
    # Load the original image
    pil_img = Image.open("pawn.black.png")
    
    
    def loading_loop(i=0):
        global tk_img
        print(f"Loop {i}")
    
        # If the prgram has loaded, stop the loop
        if i == 13: # You can replace this with your loading condition
            return
    
        # Rotate the original image
        rotated_pil_img = pil_img.rotate(30*i)
        tk_img = ImageTk.PhotoImage(rotated_pil_img)
    
        # put the rotated image inside the canvas
        canvas.delete("all")
        canvas.create_image(0, 0, image=tk_img, anchor="nw")
    
        # Call `loading_loop(i+1)` after 200 milliseconds
        root.after(200, loading_loop, i+1)
    
    
    root = tk.Tk()
    
    canvas = tk.Canvas(root)
    canvas.pack()
    
    # start the tkinter loop
    loading_loop()
    
    root.mainloop()
    

    It loads the original image then it start a tkinter loop which runs loading_loop every 200 milliseconds. Inside loading_loop, I rotate the image 30*i degrees, where i is the iteration number. Then I put the image inside the canvas.

    Notice how I only call .mainloop() once and there is no while True loop. Those are best practises for when using tkinter.

    It's best to create only 1 image inside the canvas and just reconfigure it but that will make the code longer.