Ekaterina Tcareva
Ekaterina Tcareva

Reputation: 439

How to expand a frame inside a canvas in tkinter?

I created a canvas and then a frame as a child of the canvas. I found, the I should not use pack() to put the frame in the canvas. I used

my_canvas.create_window(0,0,window=my_frame, anchor='nw')

But I would like my frame be resizable with my app. Thus, I think, I need to put something like fill=BOTH, expand=YES for my frame.

Upvotes: 0

Views: 2366

Answers (1)

fhdrsdg
fhdrsdg

Reputation: 10532

You can set the height and width of the canvas window to match the width and height of the canvas. You want to do this every time the canvas changes shape, which can be done by using a bind on the <Configure> event:

import tkinter as tk

def onCanvasConfigure(e):
    canvas.itemconfig('frame', height=canvas.winfo_height(), width=canvas.winfo_width())

root=tk.Tk()

canvas = tk.Canvas(root, background="blue")
frame = tk.Frame(canvas, background="red")

canvas.pack(expand=True, fill="both")
canvas.create_window((0,0), window=frame, anchor="nw", tags="frame")

canvas.bind("<Configure>", onCanvasConfigure)

root.mainloop()

Upvotes: 5

Related Questions