Tkinter: How to get a frame in the canvas window to expand the size of the canvas?

So I used the canvas widget in tkinter to create a frame full of shortcuts with a scroll bar. Everything works well, except that the frame expands only to the size of the labels marked in it - I want the frame to expand to the size of the parent canvas.

This can be easily done if I use the package (expand = True) (which I commented in the code below) for the frame on the canvas, but then the scroll bar does not work.

Here's the corresponding code bit:

self.canvas = Canvas(frame, bg = 'pink') self.canvas.pack(side = RIGHT, fill = BOTH, expand = True) self.mailbox_frame = Frame(self.canvas, bg = 'purple') self.canvas.create_window((0,0),window=self.mailbox_frame, anchor = NW) #self.mailbox_frame.pack(side = LEFT, fill = BOTH, expand = True) mail_scroll = Scrollbar(self.canvas, orient = "vertical", command = self.canvas.yview) mail_scroll.pack(side = RIGHT, fill = Y) self.canvas.config(yscrollcommand = mail_scroll.set) self.mailbox_frame.bind("<Configure>", self.OnFrameConfigure) def OnFrameConfigure(self, event): self.canvas.configure(scrollregion=self.canvas.bbox("all")) 

I also provided an image with color frames so you can see what I get. The pink area is a canvas that needs to be filled in with a mailbox (you can see the scroll bar on the right):

Thanks

+6
source share
2 answers

Set the binding to the canvas <Configure> event, which fires whenever the canvas is resized. From the event object, you can get the width and height of the canvas and use this to resize the frame.

+9
source

Just for future reference, if anyone else needs to know:

  frame = Frame(self.bottom_frame) frame.pack(side = LEFT, fill = BOTH, expand = True, padx = 10, pady = 10) self.canvas = Canvas(frame, bg = 'pink') self.canvas.pack(side = RIGHT, fill = BOTH, expand = True) self.mailbox_frame = Frame(self.canvas, bg = 'purple') self.canvas_frame = self.canvas.create_window((0,0), window=self.mailbox_frame, anchor = NW) #self.mailbox_frame.pack(side = LEFT, fill = BOTH, expand = True) mail_scroll = Scrollbar(self.canvas, orient = "vertical", command = self.canvas.yview) mail_scroll.pack(side = RIGHT, fill = Y) self.canvas.config(yscrollcommand = mail_scroll.set) self.mailbox_frame.bind("<Configure>", self.OnFrameConfigure) self.canvas.bind('<Configure>', self.FrameWidth) def FrameWidth(self, event): canvas_width = event.width self.canvas.itemconfig(self.canvas_frame, width = canvas_width) def OnFrameConfigure(self, event): self.canvas.configure(scrollregion=self.canvas.bbox("all")) 
+7
source

Source: https://habr.com/ru/post/984363/


All Articles