-1

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
  • What have you done to debug this? Since the canvas is in a frame, are you sure that the frame is resizing when you resize the window? Can you please provide a minimal reproducible example? Commented Jan 19, 2024 at 14:25

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.