5.9 Listboxes and Scrollbars


A listbox displays a list of strings and allows the user to select one or more of them. If the listbox contains more lines than it can display at once, the user can select the strings to be displayed by scanning the listbox. The listbox can be scanned by pressing the second mouse button and moving the mouse pointer up or down while the button is still being pressed.

A more convenient way than scanning is to use scrollbar widgets. A scrollbar widgets allows the user to determine the portion of strings displayed by moving a slider. Scrollbars are independent of a particular widget type: they can be also attached to other widgets including entries.

Figure 5.10 shows a program that allows to select a color from a list of colors. The list of colors is provided by some external file inserted at the beginning of the program. The listbox object is initialized and creates an event binding for pressing the left mouse button as follows. First the currently selected index I is retrieved (the strings in the list box are indexed). Then the string C at this index is retrieved and used as background color of the listbox widget.

L={New Tk.listbox tkInit(parent:W height:6)}
{L tkBind(event:  '<1>' 
          action: proc {$}
                     I={L tkReturn(curselection $)}
                     C={L tkReturn(get(I) $)}
                     {L tk(configure bg:C)}
S={New Tk.scrollbar tkInit(parent:W)}
<Color names>  
 proc {$ C}
    {L tk(insert 'end' C)}
{Tk.addYScrollbar L S}
{Tk.send pack(L S fill:y side:left)}

Figure 5.10: A listbox together with a vertical scrollbar.

attaching scrollbars

To attach a scrollbar to a widget we use the predefined procedure Tk.addYScrollbar. It creates event bindings for the scrollbar such that moving the scrollbar's slider affects the visible strings of the listbox. Also it creates event bindings for the listbox such that scanning the listbox is reflected by the scrollbar.

More information on listboxes can be found in listbox and more information on scrollbars in scrollbar.

Christian Schulte
Version 1.4.0 (20080702)