How do I make a button with a function which rotates an image 180 degrees? The variable my image is stored in is
img = ImageTk.PhotoImage("spidey.png")
I have already imported the PIL library's ImageTk and Image. I also want to place my image in the middle of my root window.
from tkinter import *
from PIL import ImageTK, Image
root=Tk()
root.title("Image Viewer")
root.geometry("550x650")
root.configure(background="black")
img = ImageTk.PhotoImage("spidey.png")
def rotate():
root.mainloop()
This is my code so far. Please help me out. Thanks.
I tried to write Img.rotate(180_degrees)
but it didn't work. I expected it to work the first time but it didn't. So again, please help me out.
The rotation must be applied to the image after you call Image.open
but before you call ImageTk.PhotoImage
. The parameter passed to .rotate
is just a number (representing degrees), so you'll also want Img.rotate(180)
instead of Img.rotate(180_degrees)
.
import tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
pic = Image.open("yourpic.png")
rotatedPic = pic.rotate(180)
finalPic = ImageTk.PhotoImage(rotatedPic)
label = tk.Label(master=window, image=finalImage)
label.place(x=0, y=0, width=200, height=200)
Note that you'll also need something to display the picture inside. You could use a canvas element and create_image, or (as in my example) use a widget with an image
property and assign the rotated image to that property.
This was my source for the .rotate
documentation:
https://pythonexamples.org/python-pillow-rotate-image-90-180-270-degrees/