首页 > 解决方案 > 如何旋转使用 filedialog.askopenfilename 加载的图像?

问题描述

我需要浏览图像并显示它,我已经能够做到这一点。我想在屏幕上点击一个按钮来旋转这个图像,我该怎么做?

这是我的代码:

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

非常感谢

标签: python-3.xtkinter

解决方案


rotate您可以使用 Image 对象的方法旋转图像。

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

为了使用 Image 对象,它位于 PhotoImage 的单独一行上并被称为image_object. 这image_loaded_label.image条线是为了防止垃圾收集,这会导致图像不出现。
我已将命令添加到调用rotate_image. 这将方向作为参数,然后将其转换为逆时针旋转图像的度数。的rotate方法image_object用于旋转图像,然后将其分配给image_object,替换原来的 Image 对象。然后像以前一样将其制成 PhotoImage 并配置标签以显示它。最后一行再次是垃圾收集预防。


推荐阅读