Open In App

How to Add a Scrollbar to a Group of Widgets in Tkinter

Last Updated : 13 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Tkinter, creating graphical user interfaces (GUIs) often involves arranging multiple widgets within frames or canvases. However, when the number of widgets exceeds the visible area, users may struggle to access all content. To address this, integrating scrollbars allows users to navigate through the widget group seamlessly. This article elucidates the process of adding scrollbars to a group of widgets in Tkinter, facilitating enhanced user interaction and navigation.

Using a Canvas with a Scrollbar

In this example, a canvas and a vertical scrollbar are created. The widgets are placed within a scrollable frame, which is then added to the canvas. The scrollbar's command is linked to the canvas's yview method, enabling vertical scrolling.

Python
import tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root)
scrollbar = tk.Scrollbar(root, orient="vertical", command=canvas.yview)
scrollable_frame = tk.Frame(canvas)

scrollable_frame.bind(
    "<Configure>",
    lambda e: canvas.configure(
        scrollregion=canvas.bbox("all")
    )
)

canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)

for i in range(50):
    tk.Label(scrollable_frame, text=f"Label {i}").pack()

canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")

root.mainloop()

Output:

Screenshot2024-06-08094122-ezgifcom-resize

Utilizing a ScrolledFrame Widget

Here, a ScrolledFrame widget from tkinter.ttk is employed, which automatically handles the creation and management of both the frame and scrollbar.

Python
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

frame = ttk.Frame(root)
frame.pack(expand=True, fill="both")

canvas = tk.Canvas(frame)
scrollbar = ttk.Scrollbar(frame, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas)

scrollable_frame.bind(
    "<Configure>",
    lambda e: canvas.configure(
        scrollregion=canvas.bbox("all")
    )
)

canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)

for i in range(50):
    ttk.Label(scrollable_frame, text=f"Label {i}").pack()

canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")

root.mainloop()

Output:

Screenshot2024-06-08094122-ezgifcom-resize

Next Article
Article Tags :
Practice Tags :

Similar Reads