I'm making a simple app that adds a watermark to an image. I wanted to display the image after the user selects which picture to work with. I made it using a function, the user selects a filepath and then tkinter adds a canvas with the picture. The problem is that the picture doesn't show up, the canvas is created but there's nothing inside it.
What's more confusing is that if I cut the part below out of the function and paste it before window.mainloop(), the picture will load correctly.
canvas = Canvas(width=230, height=230, highlightthickness=0)
preview_img = PhotoImage(file="something.png")
canvas.create_image(115, 115, image=preview_img)
canvas.grid(column=0, row=2)
Full code:
import PIL
from tkinter import \*
from tkinter import filedialog
import PIL.Image as Image
import PIL.ImageDraw as ImageDraw
import PIL.ImageFont as ImageFont
filepath = ""
def openFile():
global filepath
filepath = filedialog.askopenfilename(initialdir="%HOMEPATH%/Desktop")
print(filepath)
canvas = Canvas(width=230, height=230, highlightthickness=0)
preview_img = PhotoImage(file=filepath)
canvas.create_image(115, 115, image=preview_img)
canvas.grid(column=0, row=2)
def add_watermark():
\# image = Image.open("Image_created_with_a_mobile_phone.png").convert("RGBA")
image = Image.open(filepath).convert("RGBA")
txt = Image.new('RGBA', image.size, (255, 255, 255, 0))
font = ImageFont.truetype("Trajan Pro Regular.ttf", int(image.size[1] / 30))
d = ImageDraw.Draw(txt)
for i in range(1, int(font.size / 10)):
for j in range(1, int(font.size / 5)):
d.text((i * 400 - 200, j * 200 - 100), "2022", fill=(255, 255, 255, 155), font=font)
combined = Image.alpha_composite(image, txt)
combined.save("hello_world.png")
window = Tk()
window.title("Watermark adder")
window.config(padx=60, pady=30)
window.minsize(400,300)
button_open = Button(anchor="center", text="Open",command=openFile)
button_open.grid(column=0, row=0, sticky="NSEW")
button_add_watermark = Button(text="Add watermark",command=add_watermark)
button_add_watermark.grid(column=0, row=1, pady=(30,0))
window.grid_columnconfigure(0, weight=1)
window.grid_rowconfigure(0, weight=1)
window.mainloop()
I checked if the filepath functionality works and it does