Tcl/Tk GUI Programming
Lesson #2: first Tk program

Course content Enter chat room Send email 
to mailing list
Check calendar

In memory of Linda.  Worldwide Cancer sites here.    Canadian Cancer donations here.
 

Hint:

Once the programming tools have been downloaded these lessons are designed to be worked on offline.  For those of you with dialup Internet access  you might find it helpful to print off the page for each lesson and work from the printout. 

In this lesson you are going to learn how to begin to work with the graphical half to Tcl/Tk ie. the Tk part.

You are also going to learn about storing programs as simple text files to avoid having to type them into the wish console screen each and every time.
 

In the beginning ...

When computers were first invented the way you interacted with them was far from friendly.   Humans like color and graphics.   

Computers find those things a big pain in the chips.    

The simple one line program that you wrote in lesson 1 was an example of a command line or text based interface.    The input was all done with the keyboard and the output was in the form of more text on the console.   

To this day this remains one of the most economical ways to interact with a computer.   Many programmers prefer to type commands rather than use the mouse to click icons.    Nonetheless, graphics and graphical user interfaces (or GUIs as they are called) are very common on modern computers.

Fortunately for us Tcl/Tk comes with very capable and powerful graphical "sidekick": Tk.    Tk looks at the graphical world as being composed sets of what it calls widgets.    Like real world widgets, Tk widgets have a basic shape with a color, texture, size etc. 

An example of a widget would be a button.    The widget model is a good one for us as programmers because we don't have to concern ourselves with the thousands of details that go into teaching a computer how to draw buttons on the screen.

The Tk language looks after that for us.    All we have to do is decide how our button is going to look.

These characteristics of a button (called its attributes) are all modifiable from within our program.    This gives us as the programmer a very rich set of combinations of button attributes that we can use in our particular program.
 

The first step

Just as we did in our first lesson we need to clear the desktop by shrinking windows and then double click on the "wish" icon that we have on the computer desktop screen.   This should bring up two windows ... one called wish and the other called console.   If you are having difficulty with this go back and review lesson 1.

In the console window at the prompt you want to type the following line
 
button .hello -text "hi Bob"

When you have finished typing hit <enter>.   At the next prompt type:
 
pack .hello

When you hit <enter> this time the wish window should change and a button should appear.   The words "hi Bob" should appear on the face of the button .

Congratulations!  You have written your very first graphical program!    If you are thinking that this programming thing isn't all that hard after all ... you'd be partly correct.

Larger computer programs are made up of thousands of parts that are individually as simple as this line ... it is when you collect them together that things tend to get more complex.
 

Explanation of the first Tk program

Just to refresh our memory all Tcl/Tk statements are composed of:
 
command arg1 arg2 arg3 ...

In the first statement of our program the:

command = button
arg1 = .hello
arg2 = -text
arg3 = "hi Bob"
The command button specifies the type of widget we want Tk to create for us.

arg1 specifies the name we wish to give to our newly created button.

The "." in front of the name is important. 

We will describe this more fully in a future lesson ... but for now think of the "." as standing for the top level wish window.   .hello then means name the widget "hello" and put in into the toplevel wish window.

arg2 specifies one of the many attributes for this button that we want to set.    In this case we want to set the text which will appear inside the button.

arg3 then specifies the actual text string that we want to place in the "text" attribute for our button called "hello".

At this point we have only told Tk to create our button.   We have not told Tk where to draw the button on our toplevel window.    The second statement in our little program
 
pack .hello

tells Tk to draw our button widget called "hello".    When this statement gets executed our button magically appears on the wish window.
 

The second step

You have now written your first multiline program.   Computer programs would not be very useful if they had to fit all their functionality into a couple of statements.   We also don't want to have to retype our program into the console each time we want to run it.   As such we want a way to store our program as a simple text file.
 
You may be familiar with word processors on computers.   You may have used them to write a letter or do a newsletter.  

Unfortunately word processors are next to useless as a means to create and store computer programs.   

The reason for that is in order to get all those fancy fonts and things into your document, word processors actually store a lot of invisible information into the file.    The wish program has no way to understand all this invisible information when it is trying to execute statements stored in a file and gets very upset.    What we need to write our Tcl/Tk programs is a very simple program called a text editor.   

Fortunately for those using Linux there are plenty of text editors to choose from.   For those using Windows on an IBM PC or clone the best program to use is "Wordpad".    Macintosh users can use "Simple Text" (or download a very capable free program called BBedit)

Before proceding make sure that you have a folder called "level1" right inside your C drive (Macintosh users should have it right inside the harddrive).   This folder will be used to store all your programs that you create throughout this course.   (for hints on how to create a new folder click here)

What we want to do now is open up our text editor (you should have a shortcut to this program on your desktop from lesson #1).   PC users should select File:New and then "Text document" to open a new text document.   (Macintosh users should a similar sequence to open a new file).    It is very important to remember that the Wish program can only understand the most basic of text file  (no fancy fonts, bolding, underlining etc. here).

Once you have a new file opened in your editor simply  type in the two line program above and save it as a file in your "level1" folder.    While it is not required,  it is best to stick to the convention of ending Tcl/Tk program files with the

.tcl
extension.   For example we may choose to call this file
lesson2.tcl
REMEMBER: that it is very important to save this file as a straight text file.   Those Windows/Wordpad users will be prompted to specify the type of file you are saving ... select "text document".

Having saved this file we can now return to our wish console and run it by selecting the Source option from within the File menu in the console window.

This should place you in a very familar dialog box which will let you navigate up or down the folders until you arrive at the place where you stored your file above ( in your case the "level1" folder) .

If you select Open your program should run ... or does it???


 
Congratulations!  You have just stumbled on your very first Tcl/Tk program bug!
The wish program is complaining that

window name "hello" already exists in parent
The reason for this is that widgets stay around inside the wish program until we explicitly destroy them.   Because we had already created the button called "hello" in the first part of the lesson we are being told that we can't create another button widget of the same name.    Don't worry about the word parent ... in computereeze windows that start from other windows are referred to as "children" and higher level windows as "parents".    In this context "parent" simply refers to the environment in which you are running your program.

To fix our little bug we need to add another Tcl/Tk statement to the beginning of our computer program.   Here is where the file comes in really handy.   You need to return to your text editor program and load up the file where you stored your previous two statement program.   You need to open a new line at the beginning of your file and insert the follow statement.
 
destroy .hello

This tells the Tk program to get rid of the previous button widget named hello ... because we want to recreate it.

If you now save your file again and repeat the above File/Source thingy to run the program it should work like it did in step one.   In fact you can repeat this over and over again and the program will always run.

Have some fun experimenting with different strings inside the double quotes ("") on the button line in your program.   For those of you who are really ambitious try adding another attribute to the end of the button line which will set the button color.   The format for that attribute is:

-background red

Time saving hints

As you may have gathered by now programming has a healthy dose of repetition involved.   In fact the sequence of steps that you have just been through is so repeated in every programming language that is often referred to as the "Programming Cycle".   While there are many books written on this subject and many opinions as to which variation of this cycle is best in large development projects ... we fortunately do not have to concern ourselves with anything but the basics.    With our Tcl/Tk toolset our cycle consists of the following steps: While our little program had only a simple "bug" in it and with our hints it only took one iteration to solve it,  this will not always be the case for larger more complex programs.   In fact it is often very desirable to attack a complex programming problem by starting with a very simple program and adding features to it step by step.   At each step you would iterate through one complete programming cycle as described above.   If you take nothing else away from this course remember this:

    "all complex programs can be built up from simple parts which already work"

To facilitate these iterations many programmers have evolved different styles of working.    You may come up with your own which works best for you.    For me I've found that "tiling" all my windows on one screen works best .

If you leave your editor up after you save the changes then you can quickly return to it for the next iteration.

There is one more time saver that should be discussed in connection to our programming cycle.    When you run a program from the Wish console it involves several mouse operations.    It would be nice to minimize the amount of "mousing around" that you need to do to get each iteration of your program to run.   Fortunately the Wish console understands a rich set of commands to help us out.     When the Wish console is waiting for things to do it presents a "%" prompt at the start of a new line.   At the beginning of this lesson we used that to type in some Tcl/Tk statements.    The Wish console also understands a lot of other commands.   One of these is the command to set the default folder for the source.   For PC users this command is:

    cd  C:/level1

This tells the Wish console to "change directory" (directory is another name for a folder) to the C drive (another name for harddrive) and to the folder called "level1" contained there.   (Macintosh and Linux users have a similar command).  After you have typed this command in once a session, the File:Source menu will drop directly into the level1 folder for you.
 
Summary

In this lesson you have learned:


End of Lesson 2.


Copyright of iCanProgram Inc. 2002