problem on making canvas size dynamic using tkinter

39 views Asked by At

I want to make the canvas size change dynamically when the size of the size if the window changes. my canvas is in a frame and the frame is inside the root. as you can see in the code:

canvas = tk.Canvas(elementFrame, height=920, width=920, bg="lightblue") canvas.grid(row=0, column=1, pady=20)

and this is the code of the frame :

elementFrame = tk.Frame(root)
elementFrame.columnconfigure(0, weight=1)
elementFrame.columnconfigure(1, weight=1)

I tried to create a function that takes the width and the height of the window when it's dimensions change

def resize_layout(event):
    window_width = event.width
    window_height = event.heigh
    canvas.config(height=window_height - 20, width=window_height - 20)
root.bind('<Configure>', resize_layout)

it didn't work at all and the canvas disappeared

1

There are 1 answers

0
acw1668 On

With the following changes:

  • Change elementFrame.columnconfigure(0, weight=1) to elementFrame.rowconfigure(0, weight=1)
  • add sticky="nsew" to canvas.grid(...)
  • add elementFrame.pack(fill="both", expand=1)

Then you don't need to bind <Configure> event to root at all.

Simple example:

import tkinter as tk

root = tk.Tk()

elementFrame = tk.Frame(root)
elementFrame.rowconfigure(0, weight=1)
elementFrame.columnconfigure(1, weight=1)
elementFrame.pack(fill="both", expand=1)

canvas = tk.Canvas(elementFrame, width=920, height=920, bg="lightblue")
canvas.grid(row=0, column=1, padx=20, pady=20, sticky="nsew")

root.mainloop()

The canvas will be resized whenever root window is resized.