python - tkinter : Fill scrollable canvas with frame content

标签 python tkinter

我搜索了很多,但没有找到用这个内容框架正确填充可滚动 Canvas 的方法。总是有额外的空间。

在下面的代码中,在 SO 上找到并适用于一个简单的示例,我希望我的 DummyFrame 组件占据 Canvas 剩余的所有额外空间。

import Tkinter as tk

class DummyFrame(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root, borderwidth=10, background="#ff0000")
        tk.Label(self, text="DummyLabel").grid(row=0, column=0, sticky="wnes")
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

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

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

        self.vsb.grid(row=0, column=1, sticky="wnes")
        self.canvas.grid(row=0, column=0, sticky="wnes")
        self.canvas.create_window((0,0), window=self.frame, anchor="nw", 
                                  tags="self.frame")

        self.frame.columnconfigure(0, weight=1)
        self.frame.rowconfigure(0, weight=1)
        self.frame.bind("<Configure>", self.OnFrameConfigure)

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        self.populate()

    def populate(self):
        for i_row in range(50):
            #Component I want to take extra space when resizing window
            DummyFrame(self.frame).grid(row = i_row+1, column = 0, sticky="we")

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

if __name__ == '__main__':
    fenetre = tk.Tk()
    fenetre.geometry('{}x{}'.format(800, 600))
    Example(fenetre)
    fenetre.columnconfigure(0, weight=1)
    fenetre.rowconfigure(0, weight=1)
    fenetre.mainloop()

最佳答案

这个例子的命运很奇怪。因此,您在 Canvas 窗口中的框架中有 DummyFrames,而 Canvas 窗口位于框架中的 Canvas 中。很难看出这里发生了什么,以及哪个小部件维度控制了用户看到的结果维度。不过,如果您想使 DummyFrame 的宽度与您的根窗口相同(即 800 像素),只需更改 Canvas 窗口宽度即可:

self.canvas.create_window((0,0), window=self.frame, anchor="nw", 
                          width=800,
                          tags="self.frame")

关于python - tkinter : Fill scrollable canvas with frame content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28573432/

相关文章:

python - 将 pandas 中的数字格式化为以千或百万为单位的货币

python - 插入文本后文本小部件何时更新

python - 如何设置tkinter框架的透明度?

python - 如何使用 tkinter 将框架放在框架内?

python - 如何在 Python 中的日期时间值上添加秒数?

python - 使用 Pandas 错位 header 的 CSV 到 Excel

python - 框架和库是编码中更重要的部分吗?

python - SQLCODE=-30081 无法使用 python 连接到 IBM DB2 数据库

Python 3 Tkinter - 使用网格创建覆盖 100% 宽度的文本小部件

python - Tkinter 工作吗?