I need to browse an image and show it, which I'm already able to do. I'd like to rotate this image on screen clicking on a button, how can I do it?
This is my code:
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
import tkinter as tk
root = tk.Tk()
root.title('Exif Viewer')
root.geometry('500x550')
global image_loaded
def browse_image():
global image_loaded
root.filename = filedialog.askopenfilename(initialdir="/", title="Select An Image",
filetypes=(("jpeg files", "*.jpeg"), ("png files", "*.png")))
image_loaded = ImageTk.PhotoImage(Image.open(root.filename))
image_loaded_label = Label(image=image_loaded).pack()
browse_button = Button(root, padx=20, pady=5, text="Load image", command=browse_image).pack()
rotate_left_button = Button(root, padx=10, pady=5, text="Rotate left").pack()
rotate_right_button = Button(root, padx=10, pady=5, text="Rotate right").pack()
exit_button = Button(root, padx=20, pady=5, text="Exit", command=root.quit).pack()
root.mainloop()
Thanks a lot
You can rotate an image with the rotate
method of an Image object.
def browse_image():
global image_object, image_loaded_label
root.filename = filedialog.askopenfilename(initialdir="/", title="Select An Image",
filetypes=(("jpeg files", "*.jpeg"), ("png files", "*.png")))
image_object = Image.open(root.filename)
image_loaded = ImageTk.PhotoImage(image_object)
image_loaded_label = Label(image=image_loaded)
image_loaded_label.pack()
image_loaded_label.image = image_loaded
def rotate_image(direction):
global image_object
angle = {"left":90, "right":-90}[direction]
image_object = image_object.rotate(angle)
rotated_tk = ImageTk.PhotoImage(image_object)
image_loaded_label.config(image = rotated_tk)
image_loaded_label.image = rotated_tk #Prevent garbage collection
browse_button = Button(root, padx=20, pady=5, text="Load image", command=browse_image).pack()
rotate_left_button = Button(root, padx=10, pady=5, text="Rotate left", command = lambda: rotate_image("left")).pack()
rotate_right_button = Button(root, padx=10, pady=5, text="Rotate right", command = lambda: rotate_image("right")).pack()
exit_button = Button(root, padx=20, pady=5, text="Exit", command=root.quit).pack()
In order to use the Image object it is on a separate line to the PhotoImage and is called image_object
. The image_loaded_label.image
line is to prevent garbage collection, which would cause the image to not appear.
I've added commands to both buttons which call rotate_image
. This takes the direction as a parameter, which is then turned into the number of degrees anticlockwise to turn the image. The rotate
method of image_object
is used to rotate the image which is then assigned to image_object
, replacing the original Image object. Then it is made into a PhotoImage as before and the label is configured to show it. The last line is garbage collection prevention again.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments