Tkinter Scrollbar Widget

Tkinter Scrollbar Widget

In this tutorial, you’ll learn about the Tkinter Scrollbar widget and how to link it to a scrollable widget.

Introduction to the Tkinter Scrollbar Widget

A scrollbar allows you to view all parts of another widget whose content is typically larger than the available space.

The Tkinter scrollbar widget is independent and not part of any other widgets such as Text and Listbox. To use the scrollbar widget, you need to:

  1. Create a scrollbar widget.
  2. Link the scrollbar with a scrollable widget.

The following shows how to create a scrollbar widget using the ttk.Scrollbar constructor:

scrollbar = ttk.Scrollbar(container, orient='vertical', command=widget.yview)
Code copied!

In this syntax:

  • container: The window or frame where the scrollbar is located.
  • orient: Specifies whether the scrollbar is vertical or horizontal.
  • command: Allows the scrollbar widget to communicate with the scrollable widget.

Every scrollable widget has a yscrollcommand and/or xscrollcommand option, which you can assign to the scrollbar:

widget['yscrollcommand'] = scrollbar.set
Code copied!

Example: Using Scrollbars with Text Widgets

The Text widget is one of several types of scrollable widgets. The following program illustrates a simple user interface that consists of Text and Scrollbar widgets:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.resizable(False, False)
root.title("Scrollbar Widget Example")

# Apply the grid layout
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)

# Create the text widget
text = tk.Text(root, height=10)
text.grid(row=0, column=0, sticky=tk.EW)

# Create a scrollbar widget and set its command to the text widget
scrollbar = ttk.Scrollbar(root, orient='vertical', command=text.yview)
scrollbar.grid(row=0, column=1, sticky=tk.NS)

# Communicate back to the scrollbar
text['yscrollcommand'] = scrollbar.set

# Add sample text to the text widget
for i in range(1, 51):
    text.insert(f'{i}.0', f'Line {i}\n')

root.mainloop()
Code copied!

Conclusion

The Tkinter Scrollbar widget is essential for enhancing user experience in applications with large content areas. Here are the key takeaways:

  • Create a scrollbar with ttk.Scrollbar(orient, command).
  • Set the orientation to either 'vertical' or 'horizontal'.
  • Link the scrollbar to the scrollable widget using yscrollcommand or xscrollcommand.

With these features, you can effectively manage the display of large content in your Tkinter applications.