Reputation: 3058
I have the following tkinter example:
from PIL import Image, ImageTk
import tkinter as tk
root = tk.Toplevel()
container_frame = tk.Frame(master=root)
container_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
top_frame = tk.Frame(container_frame, background='red')
middle_frame = tk.Frame(container_frame, background='green')
bottom_frame = tk.Frame(container_frame, background='blue')
top_frame.grid(row=0, column=0, sticky='NSEW')
middle_frame.grid(row=1, column=0, sticky='NSEW')
bottom_frame.grid(row=2, column=0, sticky='NSEW')
container_frame.grid_columnconfigure(0, weight=1)
container_frame.grid_rowconfigure(0, weight=1, uniform='container_frame')
container_frame.grid_rowconfigure(1, weight=7, uniform='container_frame')
container_frame.grid_rowconfigure(2, weight=2, uniform='container_frame')
image = Image.open('some_image.png')
photo_image = ImageTk.PhotoImage(image)
label = tk.Label(top_frame, image=photo_image, background='yellow', anchor='w')
label.image = photo_image
label.pack(expand=1, side='left')
root.geometry('1280x720')
root.mainloop()
Unfortunately the image
within the label
has not been shrunk to fit the top_frame
correctly. Why is this?
Furthermore, when I adjust the size of the window the label
(and thus image
) is not resized at all. Again, why is this?
Thanks for any help.
Upvotes: 0
Views: 1231
Reputation: 385970
Unfortunately the image within the label has not been shrunk to fit the top_frame correctly. Why is this?
It is because that is not how tkinter works. It will not automatically grow and shrink images for you. It will grow and shrink the label, but not the image inside. You will have to write code to do that using an external library such as Pillow.
Furthermore, when I adjust the size of the window the label (and thus image) is not resized at all. Again, why is this?
As I wrote earlier, the image will never change. As for why the label doesn't change, it's because you've configured it not to change.
Consider this line of code:
label.pack(expand=1, side='left')
The expand
option says that any extra space is given to the label, which tkinter does. However, by leaving the fill
option as the default value, you've instructed tkinter to not expand the label to fill the space allocated to it.
If you want the label to grow, add fill='both'
.
Upvotes: 2