【问题标题】:Adding a scrollbar to a group of widgets in Tkinter在 Tkinter 中为一组小部件添加滚动条
【发布时间】:2011-03-06 08:50:57
【问题描述】:

我正在使用 Python 解析日志文件中的条目,并使用 Tkinter 显示条目内容,到目前为止它非常出色。输出是一个标签小部件的网格,但有时行数超过了屏幕上显示的行数。我想加一个滚动条,看起来应该很简单,但我想不通。

文档暗示只有 List、Textbox、Canvas 和 Entry 小部件支持滚动条界面。这些似乎都不适合显示小部件网格。可以在 Canvas 小部件中放置任意小部件,但您似乎必须使用绝对坐标,所以我无法使用网格布局管理器?

我尝试将小部件网格放入 Frame 中,但这似乎不支持滚动条界面,所以这不起作用:

mainframe = Frame(root, yscrollcommand=scrollbar.set)

任何人都可以提出解决此限制的方法吗?我讨厌不得不在 PyQt 中重写并将我的可执行图像大小增加这么多,只是为了添加一个滚动条!

【问题讨论】:

    标签: python tkinter tkinter.scrollbar


    【解决方案1】:

    概述

    您只能将滚动条与几个小部件相关联,而根小部件和Frame 不属于该小部件组。

    至少有几种方法可以做到这一点。如果您需要一组简单的垂直或水平小部件,您可以使用文本小部件和window_create 方法来添加小部件。这种方法很简单,但不允许对小部件进行复杂的布局。

    更常见的通用解决方案是创建一个画布小部件并将滚动条与该小部件相关联。然后,在该画布中嵌入包含标签小部件的框架。确定框架的宽度/高度并将其输入到画布scrollregion 选项中,以便滚动区域与框架的大小完全匹配。

    为什么将小部件放在框架中而不是直接放在画布中?附加到画布的滚动条只能滚动使用 create_ 方法之一创建的项目。您不能滚动使用packplacegrid 添加到画布的项目。通过使用框架,您可以在框架内使用这些方法,然后为框架调用一次create_window

    直接在画布上绘制文本项并不难,因此如果框架嵌入在画布中的解决方案看起来过于复杂,您可能需要重新考虑这种方法。由于您正在创建一个网格,因此每个文本项的坐标将非常容易计算,特别是如果每​​一行的高度相同(如果您使用的是单一字体,则可能是这样)。

    要直接在画布上绘图,只需确定您正在使用的字体的行高(并且有相应的命令)。然后,每个 y 坐标为row*(lineheight+spacing)。 x 坐标将是基于每列中最宽项的固定数字。如果你给所有的东西一个它所在的列的标签,你可以用一个命令调整一个列中所有项目的 x 坐标和宽度。

    面向对象的解决方案

    以下是使用面向对象方法的框架嵌入画布解决方案的示例:

    import tkinter as tk
    
    class Example(tk.Frame):
        def __init__(self, parent):
    
            tk.Frame.__init__(self, parent)
            self.canvas = tk.Canvas(self, borderwidth=0, background="#ffffff")
            self.frame = tk.Frame(self.canvas, background="#ffffff")
            self.vsb = tk.Scrollbar(self, 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.populate()
    
        def populate(self):
            '''Put in some fake data'''
            for row in range(100):
                tk.Label(self.frame, text="%s" % row, width=3, borderwidth="1",
                         relief="solid").grid(row=row, column=0)
                t="this is the second column for row %s" %row
                tk.Label(self.frame, text=t).grid(row=row, column=1)
    
        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()
        example = Example(root)
        example.pack(side="top", fill="both", expand=True)
        root.mainloop()
    

    程序解决方案

    这是一个不使用类的解决方案:

    import tkinter as tk
    
    def populate(frame):
        '''Put in some fake data'''
        for row in range(100):
            tk.Label(frame, text="%s" % row, width=3, borderwidth="1", 
                     relief="solid").grid(row=row, column=0)
            t="this is the second column for row %s" %row
            tk.Label(frame, text=t).grid(row=row, column=1)
    
    def onFrameConfigure(canvas):
        '''Reset the scroll region to encompass the inner frame'''
        canvas.configure(scrollregion=canvas.bbox("all"))
    
    root = tk.Tk()
    canvas = tk.Canvas(root, borderwidth=0, background="#ffffff")
    frame = tk.Frame(canvas, background="#ffffff")
    vsb = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
    canvas.configure(yscrollcommand=vsb.set)
    
    vsb.pack(side="right", fill="y")
    canvas.pack(side="left", fill="both", expand=True)
    canvas.create_window((4,4), window=frame, anchor="nw")
    
    frame.bind("<Configure>", lambda event, canvas=canvas: onFrameConfigure(canvas))
    
    populate(frame)
    
    root.mainloop()
    

    【讨论】:

    • 我正在尝试这个。首先,我只是将数据加载到框架中,然后将框架放入画布中,但窗口的大小不适合画布,并且用于确定框架几何形状的网格选项不起作用。如果我有任何进展,我会发布更新。
    • @Simon Hibbs:我添加了一个示例来说明如何做到这一点。
    • @DaniGehtdichnixan:您可以在画布上为&lt;Configure&gt; 事件创建绑定,该事件将在画布大小调整时触发。在事件处理程序中,您可以调整其中一列的 minsize 属性,使其填充整个画布(例如:self.frame.columnconfigure(1, minsize=SIZE),您可以在其中进行一些数学运算来计算 SIZE)。
    • @martineau:是的,在这种特定情况下,它工作正常,因为内部框架的内容永远不会改变。但是,作为一般解决方案,使用绑定将涵盖稍后在框架中添加更多小部件或内部框架中的小部件更改大小的情况。不过,老实说,这个示例需要在画布本身的 &lt;Configure&gt; 事件上添加 _additional_binding,以处理调整大小时的情况。
    • @stovfl:哇!这是一个错误。我不敢相信 10 多年来没有人抓住这一点。我已经修好了。
    【解决方案2】:

    使其可滚动

    使用这个方便的类使包含您的小部件的框架可滚动。请按以下步骤操作:

    1. 创建框架
    2. 显示它(包、网格等)
    3. 使其可滚动
    4. 在其中添加小部件
    5. 调用update()方法

    import tkinter as tk
    from tkinter import ttk
    
    class Scrollable(tk.Frame):
        """
           Make a frame scrollable with scrollbar on the right.
           After adding or removing widgets to the scrollable frame,
           call the update() method to refresh the scrollable area.
        """
    
        def __init__(self, frame, width=16):
    
            scrollbar = tk.Scrollbar(frame, width=width)
            scrollbar.pack(side=tk.RIGHT, fill=tk.Y, expand=False)
    
            self.canvas = tk.Canvas(frame, yscrollcommand=scrollbar.set)
            self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    
            scrollbar.config(command=self.canvas.yview)
    
            self.canvas.bind('<Configure>', self.__fill_canvas)
    
            # base class initialization
            tk.Frame.__init__(self, frame)
    
            # assign this obj (the inner frame) to the windows item of the canvas
            self.windows_item = self.canvas.create_window(0,0, window=self, anchor=tk.NW)
    
    
        def __fill_canvas(self, event):
            "Enlarge the windows item to the canvas width"
    
            canvas_width = event.width
            self.canvas.itemconfig(self.windows_item, width = canvas_width)
    
        def update(self):
            "Update the canvas and the scrollregion"
    
            self.update_idletasks()
    

    self.canvas.config(scrollregion=self.canvas.bbox(self.windows_item))


    使用示例

    root = tk.Tk()
    
    header = ttk.Frame(root)
    body = ttk.Frame(root)
    footer = ttk.Frame(root)
    header.pack()
    body.pack()
    footer.pack()
    
    ttk.Label(header, text="The header").pack()
    ttk.Label(footer, text="The Footer").pack()
    
    
    scrollable_body = Scrollable(body, width=32)
    
    for i in range(30):
        ttk.Button(scrollable_body, text="I'm a button in the scrollable frame").grid()
    
    scrollable_body.update()
    
    root.mainloop()
    

    【讨论】:

    • 我在绑定中得到一个错误,它没有绑定到任何东西,所以我用“”尝试了它。然后它似乎可以工作,但最终大小错误......如何使可滚动框架填充其父级的整个空间并动态调整大小?
    • 感谢@samkass,添加“”是正确的,这是一个错字。
    • 添加选项:body.pack(fill=tk.BOTH, expand=True)
    • 感谢您提供完整的工作示例。效果很好。在上面的评论中添加 Tarqez 会更好。
    【解决方案3】:

    扩展类 tk.Frame 以支持可滚动框架
    此类独立与要滚动的小部件替换标准tk.Frame


    import tkinter as tk
    
    class ScrollbarFrame(tk.Frame):
        """
        Extends class tk.Frame to support a scrollable Frame 
        This class is independent from the widgets to be scrolled and 
        can be used to replace a standard tk.Frame
        """
        def __init__(self, parent, **kwargs):
            tk.Frame.__init__(self, parent, **kwargs)
    
            # The Scrollbar, layout to the right
            vsb = tk.Scrollbar(self, orient="vertical")
            vsb.pack(side="right", fill="y")
    
            # The Canvas which supports the Scrollbar Interface, layout to the left
            self.canvas = tk.Canvas(self, borderwidth=0, background="#ffffff")
            self.canvas.pack(side="left", fill="both", expand=True)
    
            # Bind the Scrollbar to the self.canvas Scrollbar Interface
            self.canvas.configure(yscrollcommand=vsb.set)
            vsb.configure(command=self.canvas.yview)
    
            # The Frame to be scrolled, layout into the canvas
            # All widgets to be scrolled have to use this Frame as parent
            self.scrolled_frame = tk.Frame(self.canvas, background=self.canvas.cget('bg'))
            self.canvas.create_window((4, 4), window=self.scrolled_frame, anchor="nw")
    
            # Configures the scrollregion of the Canvas dynamically
            self.scrolled_frame.bind("<Configure>", self.on_configure)
    
        def on_configure(self, event):
            """Set the scroll region to encompass the scrolled frame"""
            self.canvas.configure(scrollregion=self.canvas.bbox("all"))
    
    

    用法:

    class App(tk.Tk):
        def __init__(self):
            super().__init__()
    
            sbf = ScrollbarFrame(self)
            self.grid_rowconfigure(0, weight=1)
            self.grid_columnconfigure(0, weight=1)
            sbf.grid(row=0, column=0, sticky='nsew')
            # sbf.pack(side="top", fill="both", expand=True)
    
            # Some data, layout into the sbf.scrolled_frame
            frame = sbf.scrolled_frame
            for row in range(50):
                text = "%s" % row
                tk.Label(frame, text=text,
                         width=3, borderwidth="1", relief="solid") \
                    .grid(row=row, column=0)
    
                text = "this is the second column for row %s" % row
                tk.Label(frame, text=text,
                         background=sbf.scrolled_frame.cget('bg')) \
                    .grid(row=row, column=1)
    
    
    if __name__ == "__main__":
        App().mainloop()
    

    【讨论】:

      猜你喜欢
      • 2022-12-03
      • 1970-01-01
      • 2013-05-24
      • 2018-05-02
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      相关资源
      最近更新 更多