    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Introduction to Tcl/Tk</title>
        <link>https://members.accu.org/index.php/journals/799</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">CVu Journal Vol 17, #2 - Apr 2005 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c97/">172</a>
                    (12)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c97-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c97+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Introduction to Tcl/Tk</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 April 2005 13:16:11 +01:00 or Sun, 03 April 2005 13:16:11 +01:00</p>
<p><strong>Summary:</strong>&nbsp;</p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e22" id="d0e22"></a></h2>
</div>
<p>There are lots of different ways to program a computer.</p>
<p>Computers are essentially very stupid.</p>
<p>Even the fastest desktop computers can only understand a hundred
or so commands in their microprocessor &quot;brains&quot;. These commands in
and of themselves are very simple things like &quot;add these two
numbers&quot;, &quot;compare these two values&quot; or &quot;fetch this value from
memory&quot;. How then could computers possibly appear to be so
&quot;smart&quot;?</p>
<p>The simple answer is that they are able to do lots of simple
things extremely quickly. So quickly that the typical desktop
computer can easily do several million such commands every
second.</p>
<p>While some people still occasionally program computers by
setting up these millions of microprocessor commands directly by
hand, you can appreciate that writing something like a computer
game or wordprocessing program in this manner would be extremely
laborious and tedious. You see humans and computers don't speak the
same language.</p>
<p>To help with this immense problem associated with programming a
computer, people began to invent tools called &quot;programming
languages&quot; and other tools to translate these &quot;human programming
languages&quot; into the language that the microprocessor
understands.</p>
<p>There are many programming languages used to program modern
computers. The one we are going to speak about in this article goes
by the name Tcl/Tk which stands for &quot;<span class=
"emphasis"><em>Tool Control Language with a Tool Kit</em></span>&quot;.
It is affectionately known by the 500000 or so users world wide by
the name &quot;tickle tee kay&quot;.</p>
<p>Tcl/Tk is a very good language to start to learn about computer
programming because:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>the language and associated tools are open sourced and hence
free</p>
</li>
<li>
<p>the language has been implemented for almost every conceivable
computer type (IBM clones, Macintosh, Linux to name but a few)</p>
</li>
<li>
<p>it has been around for over 10 years and is widely used in the
real world for everything from eCommerce on webpages to quality
control in microprocessor factories</p>
</li>
<li>
<p>it is a very simple language without too many quirky syntax
issues</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e56" id="d0e56"></a>Downloading All
Our Programming Tools</h2>
</div>
<p>The amount of work you will need to do to get set up to write
programs in Tcl/Tk will depend on the type of computer you are
using.</p>
<p>For Linux users you are likely not going to have to do anything
because Tcl/Tk tools are included with most Linux distributions
including the very popular Knoppix live CD version. Microsoft
Windows or Macintosh users, however are going to have to download
and install the Tcl/Tk tools from the Internet.</p>
<p>Tcl/Tk is maintained today by a company which goes by the name
Active State (<a href="http://tcl.activestate.com" target=
"_top">http://tcl.activestate.com</a>). All the basic tools you
will need to start exploring Tcl/Tk as a programming language are
freely available for download at the Active State website following
the link above.</p>
<p>The only other tool you will require for the code examples in
this series of articles is a very simple text editor.</p>
<p>Once again Linux and Mac users will have plenty to chose from.
For Windows users the simplest chose will be Wordpad. The important
thing to note is that you'll need a text editor and not a word
processor, as the latter adds lots of hidden characters into the
resulting file to control fonts and formatting.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e72" id="d0e72"></a>Writing Our
Very First Program</h2>
</div>
<p>At this point you should have the Tcl/Tk tools set installed on
your machine.</p>
<p>You must be anxious to write your very first computer
program.</p>
<p>We are going to be using a feature of the Tcl/Tk tools that are
not available in every computer language: the ability for the
program to be written and run interactively. In other words we are
going to type something and then immediately run the program. This
mode of programming is often called &quot;interpretive mode&quot; and it is a
great way to test out simple programs and programming
constructs.</p>
<p>The instructions below will describe how to write this program
using Windows. For others the procedure will be similar.</p>
<p>One of the tools you installed on your computer goes by the name
<span class="bold"><b>wish</b></span>. Which stands for
<span class="bold"><b>window shell</b></span>.</p>
<div class="c2"><img src=
"/var/uploads/journals/resources/findlay_console_wish_1.png" align="middle"></div>
<p>This should bring up two windows: one called <span class=
"emphasis"><em>Wish</em></span> and the other, <span class=
"emphasis"><em>Console</em></span>. The console window will usually
have a % character (this may vary though) on the left hand side of
the first line. This character is the prompt.</p>
<p>This program is going to contain the following line (to be typed
after the prompt)</p>
<pre class="programlisting">
puts stdout &quot;hi Bob&quot;
</pre>
<p>If you end the line by hitting the &lt;enter&gt; key you should
see the string inside the &quot;&quot; appear on the line below</p>
<div class="c2"><img src=
"/var/uploads/journals/resources/findlay_console_wish_2.png" align="middle"></div>
<p>Congratulations!</p>
<p>You have just written your very first Tcl/Tk program!</p>
<p>Feel free to experiment with the words inside the &quot;&quot; ... perhaps
by inserting your name.</p>
<p>Notice that you can use the &quot;up arrow&quot; key to recall the
previous line and make changes by using the &quot;left or right arrow&quot;
to edit the line.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e114" id="d0e114"></a>Explanation
of the First Program</h2>
</div>
<p>Tcl/Tk is a particularly simple language and every statement
will always have the same elements:</p>
<pre class="programlisting">
command arg1 arg2 arg3 ...
</pre>
<p>In our little programming example the command was puts. This
command is used to &quot;put things&quot; or &quot;display things&quot;.</p>
<p>The first argument in our example was: <tt class=
"literal">stdout</tt></p>
<p>For us <tt class="literal">stdout</tt> will always mean the
console screen.</p>
<p>One thing you will find is that programmers in general are a
lazy lot. The laziest programmers of the bunch are those who write
operating systems or programming languages. That is why we end up
often with cryptic commands like <tt class="literal">puts</tt> and
clipped arguments like <tt class="literal">stdout</tt> ... it saves
typing.</p>
<p>The second argument in our example was: <tt class="literal">&quot;hi
Bob&quot;</tt></p>
<p>The &quot;&quot; were used to group these words into a single argument ...
otherwise the wish program would have taken <tt class=
"literal">&quot;hi&quot;</tt> as the second argument and <tt class=
"literal">&quot;Bob&quot;</tt> as the third.</p>
<p>The <tt class="literal">puts</tt> command would only be
expecting 2 arguments and our little program would not have worked
very well. This concept of grouping is in almost every computer
language ... they don't always use &quot;&quot; as the group markers,
however. The series of words inside the &quot;&quot; are often referred to as
a &quot;string&quot; ... which is short for &quot;string of characters&quot;.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e157" id="d0e157"></a>In the Beginning
...</h3>
</div>
<p>When computers were first invented the way you interacted with
them was far from friendly.</p>
<p>Humans like colour and graphics.</p>
<p>Computers find those things a big pain in the chips.</p>
<p>The simple one line program above 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.</p>
<p>To this day this remains one of the most economical ways to
interact with a computer.</p>
<p>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.</p>
<p>Fortunately for us Tcl/Tk comes with very capable and powerful
graphical &quot;sidekick&quot;: Tk.</p>
<p>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 colour, texture, size etc.</p>
<p>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.</p>
<p>The Tk language looks after that for us. All we have to do is
decide how our button is going to look.</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>How big it will be.</p>
</li>
<li>
<p>What colour it will be.</p>
</li>
<li>
<p>What shape it will be.</p>
</li>
<li>
<p>What text will appear inside the button.</p>
</li>
</ul>
</div>
<p>These characteristics of a button are all modifiable from within
our program. This gives us a very rich set of combinations of
button attributes that we can use in our particular program.</p>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e195" id="d0e195"></a>The First
Graphical Program</h2>
</div>
<p>Just as we did above for our text program we need to be running
wish.</p>
<p>In the console window at the prompt you want to type the
following line</p>
<pre class="programlisting">
button .hello -text &quot;hi Bob&quot;
pack .hello
</pre>
<p>When you hit &lt;enter&gt; this time the wish window should
change and a button should appear. The words &quot;hi Bob&quot; should appear
on the face of the button.</p>
<div class="c2"><img src=
"/var/uploads/journals/resources/findlay_console_wish_3.png" align="middle"></div>
<p>Congratulations! You have written your very first graphical
program.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e209" id="d0e209"></a>Explanation
of the First Graphical Program</h2>
</div>
<p>Just to refresh our memory all Tcl/Tk statements are composed
of:</p>
<pre class="programlisting">
command arg1 arg2 arg3 ...
</pre>
<p>In the first statement of our program the:</p>
<pre class="programlisting">
command = button 
arg1 = .hello 
arg2 = -text 
arg3 = &quot;hi Bob&quot;
</pre>
<p>The command button specifies the type of widget we want Tk to
create for us.</p>
<p><tt class="literal">arg1</tt> specifies the name we wish to give
to our newly created button.</p>
<p><span class="bold"><b>The &quot;.&quot; in front of the name is
important.</b></span></p>
<p>We will describe this more fully shortly ... but for now think
of the &quot;.&quot; as standing for the top level window shell (wish)
window.</p>
<p><tt class="literal">.hello</tt> then means name the widget
<tt class="literal">hello</tt> and put in into the toplevel wish
window.</p>
<p><tt class="literal">arg2</tt> 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.</p>
<p><tt class="literal">arg3</tt> then specifies the actual text
string that we want to place in the <tt class="literal">text</tt>
attribute for our button called <tt class="literal">hello</tt>.</p>
<p>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</p>
<pre class="programlisting">
pack .hello
</pre>
<p>tells Tk to draw our button widget called <tt class=
"literal">hello</tt>. When this statement gets executed our button
magically appears on the wish window.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e261" id="d0e261"></a>Save the
Program</h2>
</div>
<p>As with all programs, it is a good idea to save them. You do
this as you would any text file, just following the time honoured
protocol of adding .tk as the extension. When you come to reload
the program, you should be able to run the program directly from
your filemanager - or can you?</p>
<div class="c2"><img src=
"/var/uploads/journals/resources/findlay_console_wish_4.png" align="middle"></div>
<p>The wish program is complaining that window name <tt class=
"literal">hello</tt> already exists in parent.</p>
<p>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 <tt class="literal">hello</tt> when we
typed our program into the wish console by hand, we are being told
that we can't create another button widget of the same name.</p>
<p>Don't worry about the word parent ... in computereeze windows
that start from other windows are referred to as &quot;children&quot; and
higher level windows as &quot;parents&quot;. In this context &quot;parent&quot; simply
refers to the environment in which you are running your
program.</p>
<p>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 following statement.</p>
<pre class="programlisting">
destroy .hello
</pre>
<p>This tells the Tk program to get rid of the previous button
widget named <tt class="literal">hello</tt> ... because we want to
recreate it.</p>
<p>If you now save your file again and repeat the above File/Source
procedure 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.</p>
<p>Have some fun experimenting with different strings inside the
double quotes (&quot;&quot;) 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 colour. The format
for that attribute is:</p>
<pre class="programlisting">
-background red
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e294" id="d0e294"></a>Some
Programming Wisdom</h2>
</div>
<p>As you may have gathered by now programming has a healthy dose
of repetition involved.</p>
<p>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 &quot;Programming Cycle&quot;.</p>
<p>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:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>entering/changing lines of code via our text editor</p>
</li>
<li>
<p>saving those changes to a file</p>
</li>
<li>
<p>telling the Wish console where that file is and instructing it
to Open the file and run the program</p>
</li>
<li>
<p>observing the resulting program behaviour</p>
</li>
</ul>
</div>
<p>While our little program had only a simple &quot;bug&quot; 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 article remember this:</p>
<div class="blockquote">
<blockquote class="blockquote">
<p>&quot;all complex programs can be built up from simple parts which
already work&quot;</p>
</blockquote>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e321" id="d0e321"></a>Creating Our
Own Tcl/Tk Commands</h2>
</div>
<p>Any computer language contains a relatively small set of basic
commands.</p>
<p>If that is all that the language could do it would not be very
useful or practical. It would be better if we could extend existing
commands or create entirely new ones as we needed them. Fortunately
Tcl/Tk has just that capability.</p>
<p>Before we begin we need to discuss and reinforce the
relationship between the &quot;Wish&quot; program and our little
programs.</p>
<p>Tcl/Tk is what is known as an &quot;interpreted language&quot;. What this
really means is that the statements in our little programs are
&quot;digested&quot; one by one inside the &quot;Wish&quot; program as they execute.
This has no real impact on what we are learning except that phrases
such as &quot;Tcl/Tk interpreter&quot; or &quot;interpreted by Wish&quot; etc. will
appear in the article as we go forward.</p>
<p>Suffice to remember that our programs require Wish in order to
run.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e334" id="d0e334"></a>Extended
Command Example</h2>
</div>
<p>Let us illustrate how to extend the basic Tcl/Tk commands by way
of an example.</p>
<p>Using the editor you used above create the following program by
typing in these statements:</p>
<pre class="programlisting">
# first extended command example

# scott - entry point
proc scott {mycolour} {

puts stdout [format &quot;lastcolour was %s&quot; $mycolour]

return $mycolour

} ;# end of proc scott

# main - entry point
# These statements will be executed at startup
set lastcolour red
destroy .hello

button .hello -text &quot;change me to green&quot; \
      -background red \
      -command {set lastcolour [scott $lastcolour]}
pack .hello -padx 20 -pady 20
</pre>
<p>The first thing you will notice is the statements which begin
with the # character. The Tcl/Tk interpreter program (eg. Wish)
will simply ignore these statements. This type of statement is used
to add some description to a computer program. In addition blank
lines are ignored as well with one important exception noted
below.</p>
<p>Occasionally Tcl/Tk statements get very long. Long statements
are very difficult to read because a portion of those long lines is
often &quot;off the visible screen&quot;. To make long statements more
readable Tcl/Tk has assigned the \ character a special
significance. It is often referred to as the continuation
character.</p>
<p>What the \ tells the Wish program is that the line that follows
is really to be treated as part of the same line that the \ appears
on. As such you cannot follow a line ending in \ with a blank line.
In the example above we have used the continuation character to
divide this line into two lines:</p>
<pre class="programlisting">
button .hello -text &quot;change me to green&quot; \
       -background red \
       -command {set lastcolour [scott $lastcolour]}
</pre>
<p>Notice that we have also introduced another argument for the
button widget. This argument is the <tt class=
"literal">-command</tt> argument. It is probably the single most
powerful feature of the Tk part of the Tcl/Tk language.</p>
<p>What we are saying is &quot;whenever you press the button with the
mouse jump and execute the statement enclosed by the <tt class=
"literal">{}</tt> immediately following the <tt class=
"literal">-command</tt> argument&quot;.</p>
<p>This is what allows Tk programs to actually interact with us
humans.</p>
<p>Before we try to understand the -command we have for our button
we need to understand a couple of other new Tcl/Tk ideas.</p>
<p>In Tcl/Tk variables are set using the set command. An example in
our code is:</p>
<pre class="programlisting">
set lastcolour red
</pre>
<p>In this example our variable is named <tt class=
"varname">lastcolour</tt> and the value we are assigning to that
variable is <tt class="literal">red</tt>.</p>
<p>We can then use that stored value at other places in our program
by adding a $ symbol to the front of the variable name. You can see
a couple of examples of this in the program example above. The most
interesting of these statements also merits further
explanation:</p>
<pre class="programlisting">
puts stdout [format &quot;lastcolour was %s&quot; $mycolour]
</pre>
<p>In this statement we have introduced the first of our &quot;statement
within a statement&quot; constructs. The inside statement is enclosed in
<tt class="literal">[]</tt>. The way the Wish program handles this
is that it first executes the inside statement. In this case:</p>
<pre class="programlisting">
format &quot;lastcolour was %s&quot; $mycolour
</pre>
<p>As with any Tcl/Tk statement this produces a result. The Wish
program then executes the outer statement</p>
<pre class="programlisting">
puts stdout &quot;whatever the result was from the
                                   format statement&quot; 
</pre>
<p>Compound statements are very important Tcl/Tk constructs to
understand.</p>
<p>The <tt class="literal">format</tt> statement itself is a very
powerful and important Tcl/Tk statement.</p>
<p>The <tt class="literal">format</tt> statement can be viewed as a
kind of &quot;text creation statement&quot;. It is often desirable in a
computer program to display the result of a computation or the
value stored in a variable as part of a human friendly phrase. For
this purpose we use the Tcl/Tk <tt class="literal">format</tt>
statement. If you examine the first argument to the format
statement:</p>
<pre class="programlisting">
&quot;lastcolour was %s&quot; 
</pre>
<p>You can readily identify a portion of the &quot;human friendly&quot;
phrase. In this case it would be <tt class=
"varname">lastcolour</tt> was. We would like to be able to finish
this phrase using the contents of the variable, <tt class=
"varname">mycolour</tt>. We do this by using a special format
character called a placeholder. In this case it is %s. The format
statement understands a whole range of placeholder types. The %s
means that &quot;the variable I'm holding the place for is a text
string&quot;. The third argument in our format statement identifies the
variable value that we wish to have stuffed into the spot held open
by the placeholder. In our case that is:</p>
<pre class="programlisting">
$mycolour 
</pre>
<p>The resulting phrase in our example might be something like:</p>
<pre class="programlisting">
lastcolour was red 
</pre>
<p>if the value stored in the <tt class="varname">mycolour</tt>
variable was in fact red.</p>
<p>We now have talked about all the new Tcl/Tk constructs in our
little program example with the exception of the statement:</p>
<pre class="programlisting">
proc scott {mycolour} {
</pre>
<p>The command <tt class="literal">proc</tt> in this statement is
informing the Wish interpreter program that we want to create our
very own new Tcl/Tk command. In this case we are calling our new
Tcl/Tk command <tt class="literal">scott</tt>.</p>
<p>The first matching set of <tt class="literal">{}</tt> tells Wish
that our new command will accept a single argument ... and with our
command that argument will be named <tt class=
"varname">mycolour</tt>. The single { at the end of the line
denotes the beginning of the block of Tcl/Tk code which will
constitute our new command called <tt class="literal">scott</tt>.
This logic will continue until we encounter the closing brace } as
in:</p>
<pre class="programlisting">
} ;# end of proc scott
</pre>
<p>We have introduced another form of Tcl/Tk comment here as well.
If you want to add a comment to the same line as a Tcl/Tk statement
is on you must use two characters <tt class="literal">;#</tt>
together to denote the beginning of this comment string.</p>
<p>The <tt class="literal">return</tt> statement presents the
result that we want our new <tt class="literal">scott</tt> command
to give back or return. In this simple example we are simply
returning the same value that we gave in as an argument.</p>
<pre class="programlisting">
return $mycolour
</pre>
<p>Everything between the braces constitute the logic associated
with our new command called scott.</p>
<p>In our simple example the <tt class="literal">puts</tt>
statement and the <tt class="literal">return</tt> statement are the
only statements contained within <tt class="literal">scott</tt>.
Our new commands can be as simple or complicated as we need to make
them. This capability gives our computer language a huge degree of
flexibility and richness. It is as if we can take words in our
spoken language and combine them together to create brand new words
of our own.</p>
<p>Having defined our new command we can now have it execute every
time we press the button with the mouse by adding the following to
the <tt class="literal">-command</tt> argument:</p>
<pre class="programlisting">
set lastcolour [scott $lastcolour]
</pre>
<p>Remember how the compound statements execute. Inner part first
... outer part next.</p>
<p>Go ahead and type this program in and execute it. Remember to
press the button with your mouse. You should see an output that
looks something like this:</p>
<div class="c2"><img src=
"/var/uploads/journals/resources/findlay_console_wish_5.png" align="middle"></div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e496" id="d0e496"></a>A More Useful
Example</h2>
</div>
<p>Let's go ahead now and make our little example more useful.</p>
<pre class="programlisting">
# a more useful example

# scott - entry point
proc scott {mycolour} {

puts stdout [format &quot;lastcolour was %s&quot; $mycolour]

if {$mycolour == &quot;red&quot; } {
  .hello configure -text &quot;change me to red&quot; \
                   -background green
  set newcolour green
} else {
  .hello configure -text &quot;change me to green&quot; \
                   -background red
  set newcolour red
} ;#end if else

puts stdout [format &quot;newcolour is %s&quot; $newcolour]
return $newcolour
} ;# end of proc scott

# main - entry point
set lastcolour red
destroy .hello

button .hello -text &quot;change me to green&quot; \
       -background red \
       -command {set lastcolour [scott $lastcolour]}
pack .hello -padx 20 -pady 20
</pre>
<p>What we have done in this enhanced example is added some new
statements to our <tt class="literal">scott</tt> command.</p>
<p>The first of those new constructs is what is known as the
<tt class="literal">if</tt> ... <tt class="literal">then</tt> ...
<tt class="literal">else</tt> branching construct.</p>
<p>Computers excel at this kind of true or false branching
decisions. Most of the so called &quot;intelligence&quot; in computer
software can be traced back to statements like these in the code.
The <tt class="literal">if</tt> statement allows our little program
to alter its execution path depending on the contents of a
variable.</p>
<p>It begins with the statement (and it is important that in your
code it is written this way):</p>
<pre class="programlisting">
if {$mycolour == &quot;red&quot; } {
</pre>
<p>In our little example this code block includes:</p>
<pre class="programlisting">
.hello configure -text &quot;change me to red&quot; \
                 -background green
set newcolour green
</pre>
<p>Here we have introduced our final Tcl/Tk concept for this
article ... the ability to alter the attributes on a Tk widget even
after it has been drawn on the screen.</p>
<p>We can alter the colour of our button. We can alter the text in
our button. We can do all these things based on how we code our
program logic and flow The statement which does all this magic
is:</p>
<pre class="programlisting">
.hello configure ... 
</pre>
<p>Recall that when the button was defined it was given the name
<tt class="literal">.hello</tt>.</p>
<p>Thus the <tt class="literal">.hello</tt> configure command
construct is saying &quot;I want to change something about the widget I
have called <tt class="literal">.hello</tt> ... in this case a
button widget&quot;.</p>
<p>Notice in this example we are changing the text in the button as
well as its background colour. When this statement executes that is
exactly what will happen on the screen.</p>
<p>The other statement inside our true branch of our <tt class=
"literal">if</tt> statement simply allows us to remember the new
colour we have assigned to our button.</p>
<p>The closing <tt class="literal">}</tt> for our true branch is
found as part of the <tt class="literal">else</tt> statement
below:</p>
<pre class="programlisting">
} else {
</pre>
<p>Which then moves on to the false branch as you'd expect.</p>
<p>It is hard to see from this very simple example, but this is how
computers get much of their apparent intelligence. You can see that
it isn't intelligent at all! The intelligence is all supplied by
the human programmer in the form of these true and false blocks of
code.</p>
<p>Our false branch in our code simply mirrors the true branch in
that we will alter the text and colour to reflect a red button and
remember that colour in our <tt class="varname">newcolour</tt>
variable.</p>
<pre class="programlisting">
.hello configure -text &quot;change me to green&quot; \
                 -background red 
set newcolour red 
</pre>
<p>The false branch block is ended by the single closing <tt class=
"literal">}</tt> as below</p>
<pre class="programlisting">
};# end if else 
</pre>
<p>If you now type in this program and run it you should see the
button toggle between red and green each time you click on it with
your mouse.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e588" id=
"d0e588"></a>Acknowledgement</h2>
</div>
<p>The contents of this article were derived with permission from
several of the online iCanProgram lessons offered at <a href=
"http://www.icanprogram.com/nofeecourses.html" target=
"_top">http://www.icanprogram.com/nofeecourses.html</a></p>
<p>iCanProgram offers all its courses online for no fees. All we
ask of the students is that they make a Cancer Research donation to
a local charity in memory of one of our founders.</p>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
