Previous: Using frames to improve packing
Up: Widgets
Next: Procedures
Previous Page: Using frames to improve packing
Next Page: Procedures

Using TCL code to generate widgets

Widgets can be generated explicitly, as in the example here:

label .lab1 -text "This is label 1"
      label .lab2 -text "This is label 2"
      label .lab3 -text "This is label 3"
      pack  .lab1 .lab2 .lab3

but they can also be generated by code, as in

for {set i 1} {$i<=3} {incr i 1}  {
         label .lab$i -text "This is label $i"
         pack  .lab$i
         }

Here, the for command is rather like the for command of C, and is of the form

for {initialisation} {condition} {action} {
          body
          }

Thus in this example, the initialisation sets the TCL variable i to 1, the condition tests to see whether the variable i is less than or equal to 3 before the loop body is executed, and the action increments the variable i by 1 each time round the loop.

This idea could be used for a calendar application, as in

for {set i 1} {$i <=31} {incr i 1} {
         button .button$i -width 20 -text "$i" -command "daydetails $i"
         pack   .button$i
         }

where daydetails is (an as yet undefined) TCL procedure for dealing with each of the 31 days of a month. When executed, this code gives a vertical array of 31 buttons, one for each day of the month.

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