I'm trying to get an image on a tkinter canvas to dynamically resize along with the main window.
The canvas area is expanding as I have used .pack(fill='both', expand=True)
.
I have seen a similar example using a label widget.
Similarly, I'm trying to bind canv_1.bind("<Configure>", resize_image)
Due to some error, the image is not visible on canvas. I can get the image to load only if the binding event is removed.
import tkinter as tk
from PIL import Image, ImageDraw, ImageFont, ImageTk
from tkinter import ttk
window = tk.Tk()
window.title("viewer Sample")
window.minsize(300, 225)
frm_Main = tk.Frame(master=window,
bg='#1f1e1e',
relief=tk.GROOVE,
borderwidth=2)
frm_Main.pack(fill='both', expand=True)
canv_1 = tk.Canvas(master=frm_Main)
canv_1.pack(fill='both', padx=10, pady=10, expand=True)
img2 = Image.open("beach.jpg")
img_c= ImageTk.PhotoImage(img2)
image_on_canvas= canv_1.create_image(0, 0, image=img_c, anchor='nw')
def resize_image(event):
new_width = event.width
new_height = event.height
print(new_height)
img3 = img2.resize((new_width,new_height), Image.ANTIALIAS)
photo1 = ImageTk.PhotoImage(img3)
canv_1.itemconfig(image_on_canvas, image =photo1 )
canv_1.bind("<Configure>", resize_image) # load image only when commenting this out
#Main loop
window.mainloop()