Tkinter:如何让 canvas window 中的框架扩展到 canvas 的大小?

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

所以我一直在使用 tkinter 中的 canvas 小部件来创建一个充满标签的框架,它有一个滚动条。一切都很好,除了框架只扩展到放置在其中的标签的大小 - 我希望框架扩展到父级的大小 canvas。

如果我对 canvas 中的框架使用 pack(expand = True)(我已在下面的代码中将其注释掉),则可以轻松完成此操作,但随后滚动条将不起作用。

这是适当的代码:

    ...
    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"))

我还提供了一张带有彩色边框的图片,以便您了解我的意思。粉色区域是canvas需要mailbox_frame填充的区域(可以看到右边的滚动条):

在 canvas <Configure> 事件上设置一个绑定,只要 canvas 改变大小时就会触发该事件。从事件对象中,您可以获得 canvas 宽度和高度,并使用它来调整框架的大小。

仅供将来参考,以防其他人需要知道:

        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"))

只是一个更新的答案,涵盖了水平和垂直滚动条而不破坏它们。

def FrameWidth(self, event):
    if event.width > self.mailbox_frame.winfo_width():
        self.canvas.itemconfig(self.canvas_frame, width=event.width-4)
    if event.height > self.mailbox_frame.winfo_height():
        self.canvas.itemconfig(self.canvas_frame, height=event.height-4)

仅当框架高度和宽度小于 canvas 宽度时才设置它们。尊重水平和垂直滚动条。