如何调整可滚动框架的大小以填充画布? [英] How to resize a scrollable frame to fill the canvas?

查看:106
本文介绍了如何调整可滚动框架的大小以填充画布?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想滚动的框架在左侧.我想将其扩展为同时填满".

The frame that i want to be scrollable is on the left side. I want to expand it to "fill both".

import tkinter as tk
from tkinter import *

class Example(tk.Frame):
    def __init__(self, root):

        tk.Frame.__init__(self, root)
        self.canvas = tk.Canvas(root, borderwidth=0, background="#d3d3d3")
        self.frame = tk.Frame(self.canvas, background="#ffffff")
        self.vsb = tk.Scrollbar(root, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.vsb.set)

        self.vsb.pack(side="right", fill="y")
        self.canvas.pack(side="left", fill="both", expand=True)
        self.canvas.create_window((4,4), window=self.frame, anchor="nw", 
                                  tags="self.frame")
        self.frame.bind("<Configure>", self.onFrameConfigure)
        self.pop()

    def pop(self):
        for i in range(100):
            self.f = Label(self.frame, text=i,background="#ffffff", anchor="center")
            self.f.pack(side="top", fill="both")

    def onFrameConfigure(self, event):
        '''Reset the scroll region to encompass the inner frame'''
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))


if __name__ == "__main__":
    root=tk.Tk()
    root.geometry("800x500")
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

当我使用self.frame.pack()包装所述框架时,它居中并展开,但变得无法滚动.

When i pack said frame using self.frame.pack(), it centers and expands, but it becomes un-scrollable.

如何正确包装此框架并将其用于滚动.谢谢.

How do i properly pack this frame and use it for scrolling. Thanks.

推荐答案

执行此操作的通常方法是将画布的<Configure>事件绑定到调整框架大小以适合画布的函数.

The normal way to do this is to bind the <Configure> event of the canvas to a function that resizes the frame to fit the canvas.

class Example(tk.Frame):
    def __init__(self, root):
        ...
        self.canvas.bind("<Configure>", self.onCanvasConfigure)
        ...

    def onCanvasConfigure(self, event):
        # width is tweaked to account for window borders
        width = event.width - 4
        self.canvas.itemconfigure("self.frame", width=width)
    ...

这篇关于如何调整可滚动框架的大小以填充画布?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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