Tkinter:如何在画布窗口中获取框架以扩展到画布的大小? [英] Tkinter: How to get frame in canvas window to expand to the size of the canvas?

查看:56
本文介绍了Tkinter:如何在画布窗口中获取框架以扩展到画布的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在 tkinter 中使用画布小部件来创建一个带有滚动条的充满标签的框架.除了框架仅扩展到放置在其中的标签的大小之外,一切都很好 - 我希望框架扩展到父画布的大小.

So I've been using the canvas widget in tkinter to create a frame full of labels which has a scrollbar. All is working good except that the frame only expands to the size of the labels placed in it - I want the frame to expand to the size of the parent canvas.

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

This can easily be done if I use pack(expand = True) (which I have commented out in the code below) for the frame in the canvas but then then the scrollbar doesn't work.

这是适当的代码:

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

我还提供了一张带有彩色边框的图片,这样您就可以看到我的意思了.粉色区域是需要通过mailbox_frame填充的画布(可以看到右边的滚动条):

I've also provided an image with colored frames so you can see what I'm getting at. The pink area is the canvas that needs filling by the mailbox_frame (You can see the scrollbar on the right):

推荐答案

在画布上设置绑定 事件,该事件会在画布大小改变时触发.从事件对象中,您可以获得画布宽度和高度,并使用它来调整框架的大小.

Set a binding on the canvas <Configure> event, which fires whenever the canvas changes size. From the event object you can get the canvas width and height, and use that to resize the frame.

这篇关于Tkinter:如何在画布窗口中获取框架以扩展到画布的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆