A scrollbar widget is intended to be used with any widget that is likely to be able to display only part of its contents at one time. Examples are listboxes, canvases, text widgets, and frames, amongst others.

A scrollbar widget is displayed as a movable slider between two arrows. Clicking on either arrow moves the slider in the direction of the arrow. The slider can be moved by dragging it with the cursor.

The scollbar and the widget it scrolls are connected through Tcl script calls. A scrollable widgets will have a scrollcommand attribute that is set to a Tcl script to call when the widget changes its view. When the view changes the command is called, and the command is usually set to change the state of its associated scrollbar.

Similarly, the scrollbar will have a command attribute that is another script that is called when an action is performed on the scrollbar, like moving the slider or clicking on one of its arrows. That action will be to update the display of the associated scrollable widget (which redraws itself and then invokes its scrollcommand, which causes the scrollbar to be redrawn).

How this is all done is best shown through an example:

     listbox .l -yscrollcommand ".s set" -height 10
     scrollbar .s -command ".l yview"
     for { set i 0 } { $i < 50 } { incr i } {
         .l insert end "entry $i"

creates a listbox named .l and a scrollbar named .s. Fifty strings of the form entry N are inserted into the listbox. The clever part is the way the scrollbar and listbox are linked. The listbox has its -yscrollcommand attribute set to the script ".s set". What happens is that if the view of .l is changed, then this script is called with 4 arguments attached: the number of entries in the listbox, the size of the listbox window, the index of the first entry currently visible, and the index of the last entry currently visible. This is exactly enough information for the scrollbar to work out how to redisplay itself. For example, changing the display of the above listbox could result in the following -yscrollcommand script being called:

     .s set 50 10 5 15

which says that the listbox contains 50 elements, it can display 10 at one time, the first element displayed has index 5 and the last one on display has index 15. This call invokes the set method of the scrollbar widget .s, which causes it to redraw itself appropriately.

If, instead, the user interacts with the scrollbar, then the scrollbar will invoke its -command script, which in this example is ".l yview". Before invoking the script, the scrollbar widget calculates which element should the first displayed in its associated widget and appends its index to the call. For example, if element with index 20 should be the first to be displayed, then the following call will be made:

     .l yview 20

which invokes the yview method of the listbox .l. This causes .l to be updated (which then causes its -yscrollcommand to be called, which updates the scrollbar).