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


Hello, World! in Tk

Our first Tk script is very simple. It creates a button that prints "Hello, World!" to standard output when you press it. Above the button widget is a title bar that is provided by the window manager, which in this case is twm under X windows:

Example 21-1 "Hello, World!" Tk program.

graphics/21fig01.gif

#!/usr/local/bin/wish
button .hello -text Hello \
   -command {puts stdout "Hello, World!"}
pack .hello -padx 20 -pady 10

The first line identifies the interpreter for the script:

#!/usr/local/bin/wish

This special line is necessary if the script is in a file that will be used like other UNIX command files. Chapter 2 describes how to set up scripts on different platforms.

There are two Tcl commands in the script: one to create the button, and one to make it visible on the display. The button command creates an instance of a button:

button .hello -text Hello \
    -command {puts stdout "Hello, World!"}
=> .hello

The name of the button is .hello. The label on the button is Hello, and the command associated with the button is:

puts stdout "Hello, World!"

The pack command maps the button onto the screen. Some padding parameters are supplied, so there is space around the button:

pack .hello -padx 20 -pady 10

If you type these two commands into wish, you will not see anything happen when the button command is given. After the pack command, though, you will see the empty main window shrink to be just big enough to contain the button and its padding. The behavior of the packer will be discussed further in Chapters 22 and 23.

Tk uses an object-based system for creating and naming widgets. Associated with each class of widget (e.g., Button) is a command that creates instances of that class of widget. As the widget is created, a new Tcl command is defined that operates on that instance of the widget. Example 21-1 creates a button named .hello, and we can operate on the button using its name as a Tcl command. For example, we can cause the button to highlight a few times:

.hello flash

Or we can run the command associated with the button:

.hello invoke
=> Hello, World!

Tk has widget classes and instances, but it is not fully object oriented. It is not possible to subclass a widget class and use inheritance. Instead, Tk provides very flexible widgets that can be configured in many different ways to tune their appearance. The resource database can store configuration information that is shared by many widgets, and new classes can be introduced to group resources. Widget behavior is shared by using binding tags that group bindings. Instead of building class hierarchies, Tk uses composition to assemble widgets with shared behavior and attributes.


      Previous section   Next section
    Top