0

I want to build a simple image watermark generator using Tkinter.

It will consist out of 3 parts.

  1. Upload an image
  2. Convert
  3. Download

I'm working on the first one and I'm already stuck. I dont know how to use the image that I uploaded. In this case I want to show it on the canvas on the left side of the button. How do I achieve that?

I assume after I convert it (add the watermark) I can use the same method to preview the new image.

This is the code that I'm using:

from tkinter import *
from tkinter.messagebox import showinfo
from tkinter import filedialog as fd

window = Tk()
window.title("Watermark Generator")
window.config(pady=50, padx=50, bg="#643843")

# ----- Canvas for the uploaded pic -----
canvas = Canvas(
    width=200,
    height=200,
    bg="#99627A",
    highlightthickness=0
)
canvas.grid(row=0, column=0)


# ----- Upload Action -----
def upload():
    filetypes = (
        ("PNG files", "*.png"),
        ("JPEG files", "*.jpg"),
        ("All files", "*.*")
    )

    path = fd.askopenfilename(
            title="Open an image",
            initialdir="/Desktop",
            filetypes=filetypes
    )

    showinfo(
            title="Selected image",
            message="Successfully uploaded"
    )

    image = PhotoImage(file=path)
    canvas.create_image(100, 100, image=image)


# ----- Button -----
upload_button = Button(
    window,
    text="Upload Image",
    font=("arial", 15, "bold"),
    highlightthickness=0,
    border=0,
    bg="#99627A",
    fg="#E7CBCB",
    command=upload
)
upload_button.grid(row=0, column=1, padx=30)

window.mainloop()

There are no errors, nothing is happening

Pavle
  • 19
  • 1

1 Answers1

0

This is due to an old error in Tkinter. Will probably never be fixed. We need to reference the variable img through a class.

class imageUploader:
    def __init__(self):
        self.img = ''
    
    def upload(self):
        filetypes = (
            ("PNG files", "*.png"),
            ("JPEG files", "*.jpg"),
            ("All files", "*.*")
        )

        path = fd.askopenfilename(
                title="Open an image",
                initialdir="/Desktop",
                filetypes=filetypes
        )

        showinfo(
                title="Selected image",
                message="Successfully uploaded"
        )

        self.img = ImageTk.PhotoImage(Image.open(path))
        canvas.create_image(100, 100, image=self.img)

a = imageUploader()
# ----- Button -----
upload_button = Button(
    window,
    text="Upload Image",
    font=("arial", 15, "bold"),
    highlightthickness=0,
    border=0,
    bg="#99627A",
    fg="#E7CBCB",
    command=a.upload          #note this change

It's not correct or proper, but it works.

SanguineL
  • 1,189
  • 1
  • 7
  • 18