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

2024-04-20 11:19:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想滚动的框架在左边。我想把两者都填满。在

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(),它居中并展开,但它变得不可滚动。在

如何正确打包此帧并使用它进行滚动。谢谢。在


Tags: importself框架defrootfillframeside
1条回答
网友
1楼 · 发布于 2024-04-20 11:19:10

通常的方法是将画布的<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)
    ...

相关问题 更多 >