0

I have been trying have an image viewer to integrate in a little app i was building for myself mostly.

Unfortunately, I am having a little problem with being able to resize the image dynamically. The size of the image stays fixed when I am resizing the window. Below is the code. Any help would be really appreciated.

Thanks!

import tkinter as tk
from tkinter import Label
from PIL import Image, ImageTk

# Create the root window
root = tk.Tk()
root.title("")

# App window size
screen_width, screen_height = root.winfo_screenwidth(), root.winfo_screenheight()
app_width,app_height = int(screen_width / 1.4), int(screen_height / 1.4)
app_x,app_y = (screen_width / 2) - (app_width / 2) , (screen_height / 2) - (app_height / 2)
root.geometry(f'{app_width}x{app_height}+{int(app_x)}+{int(app_y)}')

# First frame for some text
text_frame = tk.Frame(root)
text_frame.pack(side="top", fill="both", expand=True)

# Label to the first frame
label = Label(text_frame,text='Image Preview Test')
label.pack(pady=10)

# Second frame for the image
image_frame = tk.Frame(root)
image_frame.pack(fill="both", expand=True)

# Load the image
image = Image.open("pathtoimage.png")

# Keep the original aspect ratio
image.thumbnail((app_width/1.1, app_height/1.1), Image.LANCZOS)
 
image = ImageTk.PhotoImage(image)

# Label for the image
image_label = Label(image_frame, image=image, bg="#666666")
image_label.pack(fill="both", expand=True)

root.mainloop()
Kagan
  • 1
  • 1
  • The `thumbnail` method won't make an image larger, only smaller. – Mark Ransom Feb 10 '23 at 17:46
  • Does [this tutorial](https://www.tutorialspoint.com/how-to-resize-the-background-image-to-window-size-in-tkinter) help at all? – JRiggles Feb 10 '23 at 17:59
  • I am using the thumbnail method to keep the aspect ratio of the image. – Kagan Feb 10 '23 at 19:15
  • @JRiggles thanks, but unfortunately I couldn't manage to keep the aspect ratio of the image inside the frame fixed with this method. – Kagan Feb 10 '23 at 19:16
  • 1
    I tested the tutorial @JRiggles suggested and it works well, it is just a matter of calculating the size to keep the aspect ratio. `ratio = image.width / image.height` then `size = int(min(e.width, e.height * ratio)), int(min(e.height, e.width / ratio))` – Patrik Gustavsson Feb 10 '23 at 23:32
  • Does this answer your question? [Tkinter resize background image to window size](https://stackoverflow.com/questions/24061099/tkinter-resize-background-image-to-window-size) – relent95 Feb 11 '23 at 01:48

0 Answers0