Home > Software engineering >  How do I make a canvas and a photo the same size on Tkinter?
How do I make a canvas and a photo the same size on Tkinter?

Time:09-09

I'm making a photo watermark programme using Python and Tkinter. Basically it allows the user to upload a photo and create a text watermark to put over the photo.

I'm working on a function so that the user can move the text watermark to wherever they want on the photo based on the x and y coordinates. Therefore, I'm trying to have the canvas be the same height and width as the photo so the user can easily play around with the watermark placement.

However, the canvas always seems to be bigger than the photo that gets uploaded and I'm not really sure why.

Here's the code I have so far, that takes the height and width of the photo and sets them as the size of the canvas. I've then halved them for the placement of the photo uploaded so that the photo is right in the middle of the canvas.

import tkinter
from tkinter import filedialog
from PIL import ImageTk
from tkinter import *
from PIL import Image

window = tkinter.Tk()
window.title("Image Watermarker")
window.config(padx=50, pady=10, bg='#ADD8E6', width=1000, height=1000)

# Choose photo to watermark, adds to window
upload = filedialog.askopenfilename(initialdir='/', title="Select an Image",
                                    filetypes=(('png files', '*.png'), ('jpeg files', '*.jpeg')))
photo = ImageTk.PhotoImage(Image.open(upload))
h = photo.height()
w = photo.width()
canvas = Canvas(window, width=w, height=h, highlightthickness=0)
canvas.create_image((h / 2), (w / 2), image=photo, anchor=CENTER)

canvas.pack()

CodePudding user response:

Change the line to:

canvas.create_image((w/2), (h/2), image=photo, anchor=CENTER)

as you just only swapped the order of width and height.

  • Related