[Python] How to 'save as' an edited image (png) using a file dialog in tkinter and Pil in...

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to create an image editor that adds text to an image using pillow. My problem is with saving my edited image so that the user can choose the name of the save file by opening up a save-as dialog. Looking at other questions and answers, I came up with this:

    def onOpen(self):
    im = Image.open(askopenfilename())
    caption = simpledialog.askstring("Label", "What would you like the label on your picture to say?")
    fontsize = 15
    if im.mode != "RGB":
    im = im.convert("RGB")

    draw = ImageDraw.Draw(im)
    font = ImageFont.truetype("arial.ttf", fontsize)

    draw.text((0, 0),str(caption),(255,0,0),font=font)

    file = filedialog.asksaveasfile(mode='w', defaultextension=".png")
    if file:
    file.write(im)
    file.close()


    However, I get the following error when running it:

    Exception in Tkinter callback
    Traceback (most recent call last):
    File "C:\Users\Renee\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
    return self.func(*args)
    File "C:\Users\Renee\AppData\Local\Programs\Python\Python35-32\tkinterguitest.py", line 52, in onOpen
    file.write(im)
    TypeError: write() argument must be str, not Image


    I know the issue is that write can only be used with strings, so is there a command like file.write but for images? Thanks!

    Continue reading...

Compartilhe esta Página