如何调整可滚动框架的大小以填充画布?

时间:2017-05-03 17:37:21

标签: python tkinter scrollbar

我想要滚动的框架在左侧。我想将它扩展为“填充两者”。

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()打包所述帧时,它会居中和扩展,但它会变得不可滚动。

如何正确打包此框架并将其用于滚动。感谢。

1 个答案:

答案 0 :(得分:2)

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

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