Adding a scrollbar to a group of widgets in Tkinter

后端 未结 3 926
暖寄归人
暖寄归人 2020-11-21 04:43

I am using Python to parse entries from a log file, and display the entry contents using Tkinter and so far it\'s been excellent. The output is a grid of label widgets, but

3条回答
  •  难免孤独
    2020-11-21 05:02

    Make it scrollable

    Use this handy class to make scrollable the frame containing your widgets . Follow these steps:

    1. create the frame
    2. display it (pack, grid, etc)
    3. make it scrollable
    4. add widgets inside it
    5. call the update() method

    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('', 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))
    

    Usage example

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

提交回复
热议问题