Tkinter Scrollbar

Python provides several ways to create a graphical user interface. Tkinter is the most extensively used GUI technology out of all the possibilities. It’s a Python language interface to the Tk GUI toolkit offered by Python.

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

Introduction to Tkinter scrollbar widget

A scrollbar allows you to see all of another widget’s content, usually greater than the available area. The Tkinter scrollbar widget is not included in any other Tkinter widgets, including Text and Listbox. A scrollbar, on the other hand, is a separate widget.

To use the scrollbar widget, you must do the following:

  • Create a scrollbar widget first.
  • Second, create a link between the scrollbar and a scrollable widget.

This widget includes a slide controller for implementing vertically scrolled widgets like Listbox, Text, and Canvas. Entry widgets can also have horizontal scrollbars added to them.

Syntax

The easy syntax for making this widget is as follows:

w = Scrollbar ( master, option, … )

We illustrate the use of ttk.Scrollbar constructor to build a scrollbar widget below:

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

The following is the syntax:

The scrollbar is located in the container, a window, or frame. On the other hand, the orient option determines whether the scrollbar should move horizontally or vertically when scrolling.

The scrollbar widget can communicate with the scrollable widget using the command argument. In addition, the scrollable widget must inform the scrollbar of the proportion of the whole content area that is currently visible.

The yscrollcommand and/or xscrollcommand options are available in any scrollable widget. You can also customize the scrollbar. Then assign a method to it:

widget['yscrollcommand'] = scrollbar.set

Parameters

  • master − This represents the parent window.
  • options − This is a collection of the most often used widget options. These parameters can be used as key-value pairs with commas between them.

Some of the parameter options available and their descriptions are as follows:

activebackground: The color changes when the mouse is over the slider and arrowheads.

bg: The color changes
when the mouse is not above the slider and arrowheads.

bd: The width of the 3-d borders around the trough’s circumference. And the width of the 3-d effects on the arrowheads and slider. The trough has no border by default. However, the arrowheads and sliders have a 2-pixel border.

Command: When the scrollbar is shifted, this procedure is invoked.

Cursor: When the mouse is over the scrollbar, the cursor appears.

elementborderwidth: The width of the arrowheads’ and slider’s borders. The default is elementborderwidth=-1, which implies that the borderwidth option’s value is used.

highlightbackground: When the scrollbar does not have focus, this is the color of the focus highlight.

Highlightcolor: When the scrollbar has the focus, this is the focus highlight color.

Highlightthickness: The emphasis highlights thickness. Also, the default value is 1. To disable the display of the focus highlight, set it to 0.

jump: When a user drags the slider, this option determines what happens. Every minor drag of the slider typically (jump=0) causes the command callback to be called. If this option is set to 1, the callback is not be triggered until the user releases the mouse button.

orient: For a horizontal scrollbar, use orient=HORIZONTAL, and for a vertical scrollbar, use orient=VERTICAL.

repeatdelay: This setting determines how long you must keep button 1 in the trough before the slider begins moving in the same direction repeatedly. The repeatdelay=300 value is the default, and the units are milliseconds.

repeatinterval: repeatinterval

takefocus: Normally, a scrollbar widget is used to tab the focus. If you don’t want this behavior, set takefocus=0.

troughcolor: The appearance of the trough.

width: The scrollbar’s width (its y dimension if horizontal, and its x dimension if vertical). The default value is 16.

Methods

The following methods are available on scrollbar objects. We look at the respective methods and their descriptions.

get()

Returns two values (a, b) that describe the slider’s current position. For horizontal and vertical scrollbars, the a value indicates the position of the left or top edge of the slider; the b value indicates the position of the right or bottom edge.

set ( first, last )

Set w’s xscrollcommand or yscrollcommand to the scrollbar’s set() method to connect a scrollbar to another widget w. The arguments’ meaning is the same as the get() process’s returned values.

Example 1: Tkinter Scrollbar

from Tkinter import *

root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill = Y )

mylist = Listbox(root, yscrollcommand = scrollbar.set )
for line in range(100):
   mylist.insert(END, "This is line number " + str(line))

mylist.pack( side = LEFT, fill = BOTH )
scrollbar.config( command = mylist.yview )

mainloop()

Example 2: Tkinter scrollbar widget

Scrollable widgets come in a variety of forms, including text widgets. A simple user interface consisting of Text and Scrollbar widgets is demonstrated in the following program:

import tkinter as tk

from tkinter import ttk

root = tk.Tk()
root.resizable(False, False)
root.title("Codeunderscored 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='ew')

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

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


root.mainloop()
Tkinter scrollbar widget
Tkinter scrollbar widget

Key process pointers

  • Using ttk, make a scrollbar.
  • scrollingbar (orient, command)
  • Orientation can be either ‘vertical’ or ‘horizontal.’
  • The yview or xview property of the scrollable widget related to the scrollbar can be used as the command.
  • Set the scrollable widget’s yscrollcommand attribute to link to the scrollbar.

Example 3: Tkinter Scrollbar

from tkinter import *

root = Tk()
root.geometry("150x200")

w = Label(root, text ='Codeunderscored', font = "50")

w.pack()

scroll_bar = Scrollbar(root)

scroll_bar.pack( side = RIGHT, fill = Y )

mylist = Listbox(root, yscrollcommand = scroll_bar.set )

for line in range(1, 26):
	mylist.insert(END, "Code " + str(line))

mylist.pack( side = LEFT, fill = BOTH )

scroll_bar.config( command = mylist.yview )

root.mainloop()

Example 4: Tkinter Scrollbar

from tkinter import *  

top = Tk()  
sb = Scrollbar(top)  
sb.pack(side = RIGHT, fill = Y)  

mylist = Listbox(top, yscrollcommand = sb.set )  

for line in range(30):  
    mylist.insert(END, "Number " + str(line))  

mylist.pack( side = LEFT )  
sb.config( command = mylist.yview )  

mainloop()  

Tkinter Scrollbar Grid in Python

Python’s grid Tkinter is a layout manager that arranges widgets in rows and columns. The rows are represented by the x-axis, while the y-axis represents the columns. This section will look at how to use Python Tkinter’s Grid Layout Manager to add a scrollbar to the Text widget.

According to the approach, the Text and Scrollbar widget is placed at row=0 and column=0. That is for the Text widget and column=1 for the Scrollbar widget.

  • Both widgets will display parallel to each other in this manner (line 19, 27).
  • We will lengthen the scrollbar in a north-south direction using sticky (line 27).
  • Finally, we’ll connect the scrollbar to the text box widget (line 29, 30)
  • Any widget is used in place of the text widget.

Here’s how to use Grid to make a Scrollbar.

We’ve established a text editor with the Text box widget in this code, and if the quantity of words exceeds the Text widget’s orientation, a scroll bar will emerge.

from tkinter import *

window_screen = Tk()
window_screen.title('
Codeunderscored') 
window_screen.config(bg='#5F734C')

frame = Frame(
    window_screen,
    bg='#A8B9BF'
    )

text_box = Text(
    window_screen,
    height=13,
    width=32,
    font=(12)  
)

text_box.grid(row=0, column=0)
text_box.config(bg='#D9D8D7')

sBar = Scrollbar(
    window_screen,
    orient=VERTICAL
    )

sBar.grid(row=0, column=1, sticky=NS)

text_box.config(yscrollcommand=sb.set)
sBar.config(command=text_box.yview)


window_screen.mainloop()
Tkinter Scrollbar Grid in Python
Tkinter Scrollbar Grid in Python

Tkinter Scrollbar Frame in Python

In Python Tkinter, a scrollbar applies to a Frame, allowing the user to scroll the screen horizontally or vertically.

  • It is not always possible to fill the screen with all the text. Since it makes the material less readable, it will also look unattractive on the screen.
  • Scrollbars are solely created for this issue. Thus, users can now scroll through the scrollbar to access significant textual content.
  • The simplest and most effective method is to apply a scrollbar to the Frame. Put them (the scrollbar and the other widgets) into the frame window and pack them differently.
  • Pack the scrollbars on the right and other widgets on the left, for example.
  • The implementation of scrollbars on the Frame widget in Python Tkinter is shown below.
from tkinter import *

window_screen = Tk()
window_screen.title('Codeunderscored')
window_screen.geometry('400x300')
window_screen.config(bg='#5F734C')

frame = Frame(
    window_screen,
    bg='#A8B9BF'
    )

text_box = Text(
    window_screen,
    height=13,
    width=32,
    font=(12)  
)
text_box.pack(side=LEFT,expand=True)
text_box.config(bg='#D9D8D7')

sb_ver = Scrollbar(
    window_screen,
    orient=VERTICAL
    )

sb_ver.pack(side=RIGHT, fill=Y)

text_box.config(yscrollcommand=sb_ver.set)
sb_ver.config(command=text_box.yview)


window_screen.mainloop()

In Python Tkinter, we have inserted a scrollbar and a Text box widget inside the frame. Subsequently, we used Pack layout manager to move the scrollbar to the right and the textbox to the left. It is shown on lines 19 and 27. Finally, code at lines 29 and 30 binds the Scrollbar and textbox together.

Tkinter Scrollbar Canvas in Python

A canvas is a blank canvas on which diagrams are drawn. We may also use it to place images and widgets (frames, text boxes, buttons, and so on) in addition to drawing.

  • We’ll learn how to add a scrollbar to a canvas in this part.
  • We’ll also make an application to show how to use the Python Tkinter Scrollbar on Canvas.
  • Canvas is used to construct a canvas widget in the program, followed by the window’s name where it will be displayed. Also, specify the canvas window’s width and height.
Canvas(
    ws,
    width=500,
    height=400,
    )

We’ve created a frame and placed a canvas and scrollbar widget inside it. Further, we’ve bound horizontal and vertical scrollbars to the canvas.

from tkinter import *

window_screen = Tk()
window_screen.title('Codeunderscored')

theFrame = Frame(
    window_screen,
    width=500,
    height=400
    )
theFrame.pack(expand=True, fill=BOTH)

theCanvas=Canvas(
    frame,
    bg='#4A7A8C',
    width=500,
    height=400,
    scrollregion=(0,0,700,700)
    )

vertibar=Scrollbar(
    frame,
    orient=VERTICAL
    )
vertibar.pack(side=RIGHT,fill=Y)
vertibar.config(command=canvas.yview)

horibar=Scrollbar(
    frame,
    orient=HORIZONTAL
    )
horibar.pack(side=BOTTOM,fill=X)
horibar.config(command=canvas.xview)

theCanvas.config(width=500,height=400)

theCanvas.config(
    xscrollcommand=horibar.set,
    yscrollcommand=vertibar.set
    )
theCanvas.pack(expand=True,side=LEFT,fill=BOTH)

window_screen.mainloop()

Tkinter Scrollbar Text Box in Python

We’ve used Scrollbar on Text Widget in this area. This program’s output will resemble the Python Tkinter Scrollbar Frame.

  • We added the scrollbar to the Frame widget in Python Tkinter Scrollbar Frame, but we’ll apply it to the Text widget directly here.
  • In Python Tkinter, we constructed a Text widget and saved it to LEFT.
  • Then, we made a Scrollbar widget and positioned it to the RIGHT.
  • Lines 15 and 23 contain the Pack() code utilized as a layout manager.
from tkinter import *

window_screen = Tk()
window_screen.title('
Codeunderscored') 
window_screen.geometry('400x300')
window_screen.config(bg='#F25252')

theFrame = Frame(ws)

text_box = Text(
    window_screen,
    height=13,
    width=32,
    font=(12)  
)

text_box.pack(side=LEFT,expand=True)


sb_ver = Scrollbar(
    window_screen,
    orient=VERTICAL
    )

sb_ver.pack(side=RIGHT, fill=Y)

text_box.config(yscrollcommand=sb_ver.set)
sb_ver.config(command=text_box.yview)


window_screen.mainloop()

Tkinter Scrollbar in Python Isn’t Working

We’ll look at why the scrollbar isn’t working in this section. Also, while implementing the scrollbar in Python Tkinter, we’ll discuss frequent issues and how to fix them.

Missing Layout manager: If you don’t see the scrollbar on the screen, the first thing to look for is whether the scrollbar widget positioning is by the layout manager, which can be pack, grid, or in place.

Appearing Small: On the chance that the Scrollbar in Python Tkinter seems to be too small,

  • use sticky and change the scrollbar to NS for vertical Scrollbar and EW for horizontal Scrollbar if you’re using Grid layout manager.
  • Use fill=X for horizontal scrollbars and fill=Y for vertical scrollbars if you’re using Pack layout manager (s).

Tkinter Scrollbar Text Widget in Python

We’ve used Scrollbar on Text Widget in this area. This program’s output will resemble the Python Tkinter Scrollbar Frame.

  • We added the scrollbar to the Frame widget in Python Tkinter Scrollbar Frame, but we’ll apply it to the Text widget directly here.
  • In Python Tkinter, we constructed a Text widget and saved it to LEFT.
  • Then, we made a Scrollbar widget and positioned it to the RIGHT.
  • The Pack() code, utilized as a layout manager, may be found on lines 15 23.
from tkinter import *

window_screen = Tk()
window_screen.title('Codeunderscored')
window_screen.geometry('400x300')
window_screen.config(bg='#F25252')

text_box = Text(
    ws,
    height=13,
    width=32,
    font=(12)  
)

text_box.pack(side=LEFT,expand=True)


sb_ver = Scrollbar(
    ws,
    orient=VERTICAL
    )

sb_ver.pack(side=RIGHT, fill=Y)

text_box.config(yscrollcommand=sb_ver.set)
sb_ver.config(command=text_box.yview)


window_screen.mainloop()

Tkinter Scrollbar Orientation in Python

The Orient option in the Python Tkinter scrollbar allows us to change the scrollbar from horizontal to vertical positions.

  • Scrollbars are used on widgets such as text boxes, frames, and lists.
  • Vertical scrollbars, horizontal scrollbars, or both could be required.
  • The following command is used to add scrollbars.
  • The variables lb and sb refer to the list box and the scrollbar.
lb.configure(yscrollcommand=sb.set)
sb.config(command=lb.yview)

We’ve changed the scrollbar’s direction to vertical in this code, so users can now scroll up and down to access the information. Line 19 is where you’ll find the code.

from tkinter import *

window_screen = Tk()
window_screen.title('Codeunderscored') 
window_screen.geometry('400x300')
window_screen.config(bg='#4A7A8C')

theFrame = Frame(ws)
theFrame.pack(expand=True, fill=BOTH, padx=20, pady=20)

lBox = Listbox(
    frame,
    font= (12)
    )
lBox.pack(expand=True, fill=BOTH, side=LEFT)

sBar = Scrollbar(
    theFrame,
    orient=VERTICAL
    )
sBar.pack(fill=Y, side=RIGHT)

lBox.configure(yscrollcommand=sb.set)
sBox.config(command=lb.yview)

lBox.insert(0, 'Fruits')
lBox.insert(1,'Citrus – oranges, limes, grapefruits and mandarins')
lBox.insert(2,'Stone fruit – apricots, plums, peaches and nectarines')
lBox.insert(3,'Tropical and exotic – mangoes a bananasnd ')
lBox.insert(4,'Berries – kiwifruit, raspberries, strawberries, blueberries,  and passionfruit')
lBox.insert(5,'Melons – honeydew melons, watermelons and rockmelons')
lBox.insert(6, 'Vegetables')
lBox.insert(7, 'Leafy green – spinach and silverbeet, lettuce')
lBox.insert(8, 'Cruciferous – cabbage, broccoli, Brussels sprouts and cauliflower')
lBox.insert(9, 'Marrow – zucchini, cucumber and pumpkin')
lBox.insert(10, 'Root – yam, sweet potato and potato')
lBox.insert(11, 'Edible plant stem – asparagus and celery')
lBox.insert(12, 'Allium – garlic, onion and shallot')

window_screen.mainloop()

Python Tkinter code for a horizontally oriented Scrollbar

In this Python Tkinter code, we’ve constructed a horizontal scrollbar. You can see that we’ve set the scrollbar’s orientation to horizontal on line 19.

from tkinter import *

window_screen = Tk()
window_screen.title('
Codeunderscored') 
window_screen.geometry('400x300')
window_screen.config(bg='#4A7A8C')

theFrame = Frame(ws)
theFrame.pack(expand=True, fill=BOTH, padx=20, pady=20)

lBox = Listbox(
    frame,
    font= (12)
    )
lBox.pack(expand=True, fill=BOTH)

sBar = Scrollbar(
    theFrame,
    orient=HORIZONTAL
    )
sBar.pack(fill=X)

lBox.configure(xscrollcommand=sb.set)
sBar.config(command=lb.xview)

lBox.insert(0, 'Not all heros wear capes.')
lBox.insert(1, 'Game changers are in blue')
lBox.insert(2, 'With great power comes great responsibility')
lBox.insert(3, 'A noun phrase has a noun or pronoun as the main word')
lBox.insert(4, 'With great power comes great responsibility')
lBox.insert(5, 'contribute to open source, as this will help & motivate you.')

window_screen.mainloop()

We’ve set the scrollbar’s orientation to horizontal in this output. Users can now view the material by scrolling right and left.

text_box.config(yscrollcommand=sb.set)
sb.config(command=text_box.yview)

Conclusion

The scrollbar widget is responsible for scrolling down the content of other widgets such as listboxes, text boxes, and canvases. The horizontal scrollbars can, however, be added to the Entry widget.

A Scrollbar alludes to a Python Tkinter widget that allows continuous data to be scrolled across the screen in a preset direction. The direction can be vertical or horizontal. Scrollbars are added when the content exceeds the screen orientation to allow the user to navigate to previously viewed information in either a right-to-left or upward-to-downward direction.

In Python, layout managers like Place(), Grid(), and Pack() are used to position Tkinter widgets. These techniques are used to place the scrollbar widget on the application window.

Similar Posts

One Comment

  1. You may have good knowledge. But you are not good at teaching. You must give examples with output. I need help to insert scroll bar at the bottom of candle chart in python 3.11.3.

Leave a Reply

Your email address will not be published. Required fields are marked *