Search code examples
imagetkinterpython-imaging-libraryimage-resizing

resize image in Tkinter (Python 3.10)


I have searched and searched but I just cant find the right answer for my problem so I am hoping to find some help here.

Im trying to intergrate an image in Tkinter with the help of PIL but it just does not resize the image correctly.

from tkinter import *
import PIL.ImageTk
from PIL import Image

window = Tk()
window.title('Title')
window.config(padx=100, pady=100, bg=GREEN)

canvas = Canvas(width=300, height=200, bg=GREEN, highlightthickness=0)
size = (50, 150)
image = Image.open('lock.png')

image = image.resize(size)
pic = PIL.ImageTk.PhotoImage(image)
canvas.create_image(180, 250, image=pic)
canvas.grid(column=1, row=1)

window.mainloop()

how it looks like

I would like the picture in the middle, smaller than it is. But it gets cut not resized.

Please help Thanks in advance!


Solution

  • The canvas size is 300x200, but you put the center of the image at (180, 250). So only part of the top of the image is shown, that is why the image is cropped.

    You need to put the image at (150, 100) if you want it to be at the center of the canvas.

    canvas.create_image(150, 100, image=pic)
    

    Note that the image is resized actually.