python-3.x - 如何旋转使用 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()
非常感谢
解决方案
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 并配置标签以显示它。最后一行再次是垃圾收集预防。
推荐阅读
- oracle - 查找序列在删除之前生成的最后一个数字
- variables - 模拟重复二元测量的数据
- java - 如何根据输入行的多个条件从扫描仪输入中读取预定义的行数
- javascript - 使用 Jquery 隐藏字段时绕过表单验证
- jenkins - 你如何使用 Jenkins libraryResource 从资源中读取文件?
- c++ - 为什么这个全局二元运算符不能推导出模板参数?
- r - 为 TRUE 值定义一个“缓冲区”,如果在“缓冲区”内,则将 TRUE 变为 FALSE
- intellij-idea - IntelliJ IdeaVIM 自动完成干扰 jj ESC
- javascript - 仅当键存在时,才将 $push 值与 mongoose 一起放入数组
- android - 无法解析符号 ViewModel