Previous: Widget hierarchy
Up: Widgets
Next: Command binding
Previous Page: Widget hierarchy
Next Page: Command binding

Widget binding

Widgets such as entry and text widgets have an implicit binding to their text variable, so that as the data changes within the widget, the text variable is automatically kept up to date. It is also possible to explicitly bind together a widget with an event to produce an action.

This means that whenever the cursor is placed over an active widget, and a specified event takes place, an appropriate action can be generated. Events can be of several kinds, including mouse movement, button presses, button releases, multiple button clicks, and keyboard data entry. Note, there can be multiple events associated with a widget, each having a different associated action.

The instruction to bind a widget to an action is the bind command. An example is given here using a frame widget:

frame .frame1 -width 100 -height 100
     bind .frame1 <Button-1> {puts "frame1: Button 1 pressed"}
     bind .frame1 <Button-2> {puts "frame1: Button 2 pressed"Ó}
     bind .frame1 <Button-3> {puts "frame1: Button 3 pressed"Ó}
     bind .frame1 <ButtonRelease-1> {putsÒ"frame1: Button 1 released"}
     bind .frame1 <Double-Button-1>  
                     {puts "frame1: Double click Button 1"}
     bind .frame1 <Any-Motion> {puts "frame1: pointer at %x,%y"}
     pack .frame1

The following example is more complex, and shows how selections can be made from a listbox, using the mouse.

#Set up a listbox to show rainbow colours
   #and demonstrate selection
   listbox .listbox2 -exportselection 1
   pack .listbox2

#The following is an example of a widget specific command -this is #the insert operation for listboxes, which inserts a list of #items starting at line 0 .listbox2 insert 0 red orange yellow green blue indigo violet

#There are no pre-declared bindings for the listbox #Now bind a button release event on button 1 to the widget #This will NOT interfere with the selection process! bind .listbox2 <ButtonRelease-1> {showindices}

#Now define procedure to show selected indices proc showindices {} { puts [.listbox2 curselection] }

Clearly in practical applications, more useful action bindings will be associated with each event. Care should be taken with event bindings, since some widgets may have bindings set up which could be inadvertently changed - for example, button widgets often have a command associated with a button 1 press, so binding to a button 1 press will cause the previous binding to be overridden.



Previous: Widget hierarchy
Up: Widgets
Next: Command binding
Previous Page: Widget hierarchy
Next Page: Command binding

csstddm@brunel.ac.uk
Fri Aug 19 16:55:19 BST 1994