Scrollbars provide an essential way to enable scrolling through content that exceeds available screen space. Tkinter provides versatile scrollbar widgets that you can customize and link to textual, graphical, and custom widgets.
In this comprehensive Tkinter scrollbar guide, we will cover:
- Common real-world use cases for scrollbars
- Adding vertical and horizontal scrollbars
- Attaching scrollbars to textual, graphical and custom widgets
- Handling mouse and keyboard scrolling events
- Implementing auto-hide and auto-show scrollbars
- Customizing scrollbars with styles, colors and behavior
- Building high performance scrolling areas with Canvases
- A scrollable frame subclass for scrolling all kinds of widgets
- Common scrollbar mistakes and how to avoid them
Let‘s get started with some motivating use cases that demonstrate how scrollbars create better user experiences.
Key Use Cases for Adding Scrollbars
Here are some common examples that benefit from the addition of Tkinter scrollbars:
Data Tables – Tabular data that expands across too many rows/columns for the window size. Scrollbars allow easy navigation.
Text Editors – Key for handling documents that are longer than visible area. Provides precise control.
Image Galleries – Enable smooth scrolling through collections of images in a compact frame.
File Browsers – Exploring deep folder hierarchies via scrollable file lists.
Real-time Data – Stream new logs/messages while preserving context via scrolling.
Plots and Charts – Interactively scroll historical portions of a live time-series plot.
As you can see, scrollbars serve many scrolling needs ranging from boring data tables to flashy multimedia apps.
Now let‘s see how to add scrollbars in Tkinter…
Adding a Vertical Scrollbar
Import Tkinter and create the root window:
import tkinter as tk
root = tk.Tk()
Then instantiate a Scrollbar widget, with root as the parent. Set the orient option to "vertical":
scrollbar = tk.Scrollbar(root, orient="vertical")
scrollbar.pack(side="right", fill="y")
Here we pack the scrollbar to the right with fill set to "y" so it spans vertically.
Next add a widget to control scrolling on like Text or Canvas:
text = tk.Text(root)
text.pack(side="left", fill="both", expand=True)
Now link them together by configuring their yview and yscrollcommand callbacks:
text.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=text.yview)
This synchronizes scrolling between the two widgets. You can customize the scrollbar style and behavior before linking it. But this exemplifies the basic pattern – create scrollbar, add scrollable widget, link scroll commands.
Adding a Horizontal Scrollbar
Adding a horizontal scrollbar follows the same core approach with a few modifications:
- Set
Scrollbarorient to"horizontal" - Use
xviewinstead ofyview - Configure
xscrollcommandinstead ofyscrollcommand - Pack fill and expand options for the
"x"axis
Here is an example attaching a horizontal Tk scrollbar to a Text widget:
import tkinter as tk
root = tk.Tk()
text = tk.Text(root)
text.pack(fill="both", expand=True)
scrollbar = tk.Scrollbar(root, orient="horizontal")
scrollbar.pack(fill="x")
text.config(xscrollcommand=scrollbar.set)
scrollbar.config(command=text.xview)
Now you can scroll the Text widget left and right using the horizontal scrollbar.
This same process applies for adding horizontal and vertical scrollbars to any widgets that support scrolling including Listbox, Canvas, and more.
Attaching Scrollbars to Other Widgets
While Text is a common scrollbar use case, we can scroll virtually anything with a scrollbar including images, plots, file lists, custom widgets, and more.
Here is an example vertical scrollbar linked to a Canvas for scrolling graphics:
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=800, height=500)
canvas.pack(side="left", fill="both", expand=True)
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side="right", fill="y")
canvas.configure(yscrollcommand=scrollbar.set)
scrollbar.config(command=canvas.yview)
We set up the canvas based on our graphical needs, then add and connect a scrollbar to enable scrolling vertically through potentially infinitely long canvas space.
You can use this exact same recipe to overlay scrollbars onto a wide variety of widgets:
Listbox– Scroll through long lists- Image labels – Scroll galleries or collections
- Plot widgets – Pan through historical graphs
- File browser – Navigate directory tree
- Custom widgets – Add legacy scrollbars
As long as the widget supports the xview/yview scroll command API, you can sync it with a scrollbar. This provides a standard scrolling UX for navigating all kinds of content.
Now let‘s look at some more advanced capabilities…
Handling Scroll Events from Mouse and Keyboard
There may be cases where you want to trigger scrolling from the mouse wheel or keyboard in addition to the scrollbar.
We can set bindings on widgets to handle mouse and keyboard events and translate them into scroll commands:
def on_mousewheel(event):
canvas.yview_scroll(int(-1*(event.delta/120)), "units")
root.bind_all("<MouseWheel>", on_mousewheel)
This enables mousewheel scrolling by moving the canvas view vertically. The key thing is calling yview_scroll to update positioning.
Similarly we can handle keys like Page Up/Page Down:
def handle_keys(event):
if event.keysym == "Next":
canvas.yview_scroll(1, "pages")
elif event.keysym == "Prior":
canvas.yview_scroll(-1, "pages")
root.bind("<Key>", handle_keys)
Here we bind keyboard events, check for page up/down keys and convert those into scroll canvas view calls.
Supporting these additional scroll interactions enhances application usability.
Implementing Auto-Hide and Auto-Show Scrollbars
By default scrollbars remain visible even when content fits without scrolling required. This wastes space.
We can instead create scrollbars that automatically show and hide based on scrolling needs:
Auto Hide Scrollbars
import tkinter as tk
root = tk.Tk()
text = tk.Text(root)
scrollbar = tk.Scrollbar(root, orient="vertical", side="right")
...
scrollbar.pack(fill="y", side="right", expand=True)
Here the key points are:
- Set an explicit
sideparam onpack/grid - Specify
expand=Falseon the scrollbar layout
This positions the scrollbar off-canvas until you actively scroll when it slides into view.
Auto Show Scrollbars
We can also make unused scrollbars completely disappear but show automatically when scrolling:
scrollbar.pack_forget()
def on_scroll(event):
scrollbar.pack()
text.bind("<MouseWheel>", on_scroll)
Now the scrollbar starts hidden from view. But as soon as any scroll event occurs like a mouse wheel tick, we pack the scrollbar which makes it visible.
You can use these techniques to conserve screen real estate while still providing scrollbars only when needed.
Building High Performance Scrolling Areas with Canvas
When implementing scrolling for high volume dynamic data or multimedia, the Canvas can deliver better performance through hardware acceleration.
Here is an example recipe for a smooth scrollbar-driven canvas scrolling area:
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=800)
canvas.pack(side="left", fill="both", expand=True)
scrollbar = tk.Scrollbar(root, command=canvas.yview)
scrollbar.pack(side="right", fill="y")
canvas.configure(yscrollcommand = scrollbar.set)
for i in range(100):
canvas.create_text(100, i*20, text="Line %s" % i)
canvas.config(scrollregion=(0,0,500, 2000))
The key aspects that improve canvas scrolling performance are:
- Use create_ commands to add graphical content
- Update scrollregion parameter to actual data size
- Avoid packing graphical elements inside Canvas frames
Together these enable smooth GPU-powered scrolling of vast amounts of data.
Introducing the Scrollable Frame
While scrollbars work great with standard widgets like Text and Canvas, adding scrollbars to arbitrary widgets can involve custom event handling.
Tkinter provides a useful ScrolledFrame class that enables scrolling virtually any kind of widget via a frame subclass:
text = tk.Text(root)
scrolled_frame = ScrolledFrame(root)
scrolled_frame.pack()
scrolled_frame.window_create("Text", window=text)
scrolled_frame.resize_scrollregion()
This wraps any widget in a scrollable frame with just a few lines for immediate scrolling support.
The key abilities include:
- Auto resize scroll region as contents change
- Support for windowing widgets like Text
- Vertical and horizontal scrolling
- Mousewheel, keys handled out of box
- Simple migration of widgets into scrollbars
Overall the ScrolledFrame provides a handy way to retrofit scrolling onto Tk interfaces without custom event integration code.
Common Scrollbar Mistakes To Avoid
While scrollbars are simple to add in Tkinter, there are a few common mistakes that come up:
Sizing Issues – Forgetting to account for scrollbar width in window padding. Causes interface truncation.
Laggy Scrolling – Failing to update scrollregion for dynamic data. Causes blank area artifacts.
Scope Issues – Trying to access scrollbar from outside class. Use attributes for access.
Grid Align – Placing grid scrollbars without row/colspan alignment. Causes shrinking.
Scale Limits – Limiting slider min size causes difficult target for interaction.
The key is sizing the entire app content anticipating any scrollbars to avoid truncation. And for dynamic data force an update of the scrollable region dimensions.
Customizing Scrollbar Style and Behavior
Beyond standard vertical scroll next to widgets, there are a variety of scrollbar orientations, styles and customization options we can apply:
fancy_scrollbar = tk.Scrollbar(root,
orient="horizontal",
width=16,
troughcolor="darkgrey",
troughrelief="groove",
activerelief="ridge"
repeatdelay=300,
command=text.xview)
Here we customize:
- Orientation – Vertical, horizontal or both
- Width – Dimensions of the scrollbar
- Trough settings – Color, border style
- Active relief – 3D border effect when scrolling
- Repeat delay – Time before continuous scroll
- Command – Widget view method to update
You can also completely restyle scrollbars using styling frameworks like ttkthemes or style sheets. This enables scrollbars to match any aesthetic.
Additional options like arrow color, slider length, increment size allow dialing in scroll behavior. Test different configurations to find optimal scrolling ergonomics.
Conclusion
As we have seen, Tkinter provides exceptional support for adding scrollbars to handle widgets and data sets that exceed available screen size.
The key patterns include:
- Instantiating
Scrollbarwidgets - Packing scrollbars alongside or overlayed onto content widgets
- Linking scroll commands like
yviewandyscrollcommand - Customizing scrollbar style and behavior
Common use cases that benefit from Tkinter scrollbars range from text editors and file browsers to multimedia galleries, plotting dashboards and more.
By mastering various scrollbar techniques – auto hide/show, high performance Canvas scrolling, event bindings and scrollable frames – you can create intuitive navigation for diverse data visualization and interaction needs.
The result is Python GUI applications with engaging user experiences spanning everything from boring business forms to flashy multimedia dashboards.


