首页 > 解决方案 > 将`askedfilename`函数中的图片保存到tkinter python中的本地

问题描述

我的意图是在我导入到 tkinter 的图像上创建一个应用程序写入(条目标签)并使用“asksaveasfilename”导出,以询问用户他们想要保存为什么格式。

我试过'image.save()'

#!/use/bin/env python3
import os
import tkinter
import webbrowser
from tkinter import *
from tkinter.filedialog import asksaveasfilename
from tkinter.scrolledtext import ScrolledText
from PIL import Image, ImageTk
from PIL import *

window = tkinter.Tk()
window.geometry("520x800")
window.title("STARLABS BIOSCIENCE SDN BHD")
window.resizable(False, False)
window.config(background="#150051")

MENUBAR = Menu(window)
window.config(menu=MENUBAR)

image = Image.open("s.jpg")
photo = ImageTk.PhotoImage(image)
label = Label(window, image=photo, text="").pack()
venuelabel = Label(window, text="Venue: ", background="#150051", font=("bold", 13,)).place(x=0, y=660)
contactLabel = Label(window, text="Contact: ").place(x=0, y=720)
dateTEXT = Entry(window, width=35, ).place(x=170, y=380)
Venue = ScrolledText(window, width=35, background="#150051").place(x=57, y=660, height=60)
person = Entry(window, width=35).place(x=57, y=720)


# function :
def exitWindow():
    window.destroy()


def save():
    print("save")
    dialogue = image.filename = asksaveasfilename(initialdir="/", title="Select file", filetypes=(
        ('JPEG', ('*.jpg', '*.jpeg', '*.jpe')), ('PNG', '*.png'), ('BMP', ('*.bmp', '*.jdib')), ('GIF', '*.gif')))
    image.save("picture.jpg")


# Add Menu Items:
file_menu = Menu(MENUBAR, tearoff=0)
file_menu.add_cascade(label="Save", command=save)
addon = Menu(file_menu, tearoff=0)
addon.add_command(label="SAVE TO FILE")
addon.add_command(label="Email To")
file_menu.add_command(label="Exit", command=exitWindow)
MENUBAR.add_cascade(label="File", menu=file_menu)

window.mainloop()

提前致谢。

标签: pythonimagetkintersave

解决方案


Image.save是正确的,但您需要ImageGrab先到屏幕并裁剪图像。现在你只是保存你打开的图像。

from PIL import ImageGrab
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
tk.Entry(root).pack()

def save_pic():
    result = filedialog.asksaveasfilename(initialdir="/", title="Select file", filetypes=(
        ('JPEG', ('*.jpg', '*.jpeg', '*.jpe')), ('PNG', '*.png'), ('BMP', ('*.bmp', '*.jdib')), ('GIF', '*.gif')))
    if result:
        x = root.winfo_rootx()
        y = root.winfo_rooty()
        height = root.winfo_height() + y
        width = root.winfo_width() + x
        ImageGrab.grab().crop((x, y, width, height)).save(result)

tk.Button(root,text="Click me",command=save_pic).pack()

root.mainloop()

推荐阅读