www.gibmonks.com

  Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 21.  Tk Fundamentals


Configuring Tk Widgets

Example 21-1 illustrates a style of named parameter passing that is prevalent in the Tk commands. Pairs of arguments specify the attributes of a widget. The attribute names begin with -, such as -text, and the next argument is the value of that attribute. Even the simplest Tk widget can have a dozen or more attributes that can be specified this way, and complex widgets can have 20 or more attributes. However, the beauty of Tk is that you need to specify only the attributes for which the default value is not good enough. This is illustrated by the simplicity of the Hello, World example.

Finally, each widget instance supports a configure operation, which can be abbreviated to config, that can query and change these attributes. The syntax for config uses the same named argument pairs used when you create the widget. For example, we can change the background color of the button to red even after it has been created and mapped onto the screen:

.hello config -background red

Widget attributes can be redefined any time, even the text and command that were set when the button was created. The following command changes .hello into a goodbye button:

.hello config -text Goodbye! -command exit

Widgets have a cget operation to query the current value of an attribute:

.hello cget -background
=> red

You can find out more details about a widget attribute by using configure without a value:

.hello config -background
=> -background background Background #ffe4c4 red

The returned information includes the command-line switch, the resource name, the class name, the default value, and the current value, which is last. The class and resource name have to do with the resource mechanism described in Chapter 28. If you only specify configure and no attribute, then a list of the configuration information for all widget attributes is returned. Example 21-2 uses this to print out all the information about a widget:

Example 21-2 Looking at all widget attributes.
proc Widget_Attributes {w {out stdout}} {
   puts $out [format "%-20s %-10s %s" Attribute Default Value]
   foreach item [$w configure] {
      puts $out [format "%-20s %-10s %s" \
         [lindex $item 0] [lindex $item 3] \
         [lindex $item 4]]
   }
}

      Previous section   Next section
    Top