如何在python中使用tkinter上的save按钮保存图像

如何在python中使用tkinter上的save按钮保存图像,python,numpy,tkinter,python-imaging-library,cv2,Python,Numpy,Tkinter,Python Imaging Library,Cv2,我试图使用tkinter使“另存为”按钮将图像保存到某个位置目录中,但遇到了一个问题 from tkinter import * from tkinter import ttk from tkinter import filedialog from PIL import ImageTk, Image, ImageDraw import cv2 import numpy as np img = cv2.imread('face_person1.jpg') # convert the images

我试图使用tkinter使“另存为”按钮将图像保存到某个位置目录中,但遇到了一个问题

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from PIL import ImageTk, Image, ImageDraw
import cv2
import numpy as np

img = cv2.imread('face_person1.jpg')
# convert the images to PIL format...
edged = Image.fromarray(img)

edged = ImageTk.PhotoImage(edged)

def savefile():
    hsl = Image.open(edged)
    hsl = filedialog.asksaveasfile(mode='w', defaultextension=".jpg")
    if hsl is None:
        return
    sv = edged.save()
    sv.close()


button = Button(text="save as", command=savefile)
button.pack()
错误消息是:

Exception in Tkinter callback fp = io.BytesIO(fp.read())
AttributeError: 'numpy.ndarray' object has no attribute 'read'

要保存图像,您必须使用
PIL.image
,因此不要将
PhotoImage
分配给用于保存
PIL.image的变量

edge = Image.fromarray(img)

tk_edge = ImageTk.PhotoImage(edge)
您必须使用文件名来保存它

edge.save(filename)
完整的工作示例

import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from PIL import ImageTk, Image, ImageDraw
import cv2
import numpy as np

# --- functions ---

def savefile():
    filename = filedialog.asksaveasfile(mode='w', defaultextension=".jpg")
    if not filename:
        return
    edge.save(filename)

# --- main ---

root = tk.Tk()

img = cv2.imread('face_person1.jpg')
edge = Image.fromarray(img)

tk_edge = ImageTk.PhotoImage(edge)
label = tk.Label(root, image=tk_edge)
label.pack()

button = tk.Button(root, text="save as", command=savefile)
button.pack()

root.mainloop()

尝试将代码设置为在没有Tkinter的情况下工作(例如,使用硬编码的输出文件名)因此,您可以查看异常的整个上下文。如果您想保存它,因为
ImageTk.PhotoImage
没有保存它的功能,请不要对
PIL.Image
ImageTk.PhotoImage
使用相同的变量
edge
。你必须保存
PIL.Image
如果你想保存它,你不必打开它。如果变量中有图像,则不要将名称分配给变量
hsl