Unit 5
Unit 5
Example:
#!/usr/bin/tclsh
Puts "Hello World"
Script execution
$ chmod +x [Link]
$ ./[Link]
In TCL, “Puts” Command is used to print messages to the console .syntax of puts is
below
Ex:
1. Command substitution
2. Variable substitution
3. Backslash substitution
Command substitution
Example:
Here the command between the square brackets is evaluated first. The results is returned
.”expr” used for performing the arithmetic calculation.
Variable substitution
#!/usr/bin/tclsh
set a 10
puts a
puts $a
Here we create a variable called “a” and set value “10” to it.
• puts a : It will print string “a” but not the value of ‘a’ to the console
• puts $a : It will print the value of ‘a’ to the console
Let’s execute and verify it. You will get the output as below.
$ ./[Link]
a
10
Backslash substitution
In Tcl, the backslash is used for escaping special characters as well as for spreading long
commands across multiple lines. Any character immediately following the backslash
will stand without substitution. In the example below, you can see special character ” “,
remains after the backslash.
#!/usr/bin/tclsh
puts "This is my \"car\"
$ ./[Link]
This is my "car"
NOTE: To comment any string in TCL “#” is used. All characters after the “#” are
ignored by tclsh shell command.
TCL Variable
A variable is an identifier which holds a value. In other words, a variable is a reference
to a computer memory, where the value is stored.
Variables are created by “set command” and all variable names are case sensitive. It
means hello, Hello, HELLO all are different in TCL. Look at some example for case
sensitive variable.
Output:-
puts $name
Technoit
puts $Name
Technoit_1
puts $NAME
Technoit_2
Set a 10
put $a
10
The “set” command is used to create and read variables as shown above. The unset
command is used to destroy a variable. The “info exists” command returns 1 if varName
exists as a variable (or an array element) in the current context, otherwise returns 0. ( see
example below).
There are various “info” command in TCL like “info exists”, “info functions”, “info
global”, and so on. Here we will see an example of “info exists”.
Ex:
set a 20
puts $a
20
unset a
puts [info exists a]
0
Different braces and their behavior
Curly braces in TCL group words together to become arguments. Curly braces are used
to define a block that’s deferred – in other words, it may be run AFTER the rest of the
command on the current line. Characters within braces are passed to a command exactly
as written.
Example:
set x 10
puts {$x}
$x
set number {1 2 3 4 5} -> Here number is a list data type
puts $number
OUTPUT: 1 2 3 4 5
[ ] square braces
Square brackets are used to create nested command. Simply put, output of one command
passed as argument to another command. Square brackets are used to define a block
that’s run BEFORE the rest of the command on the current line, and the result is
substituted into the line.
Ex: –
set x 10
puts "y : [set y [set x 10]]"
puts "x : $x"
OUTPUT→ y : 10
x : 10
( ) round braces
This command is used to create array data type and also indicate operator precedence.
set a(1) 10
set a(2) 20
Here “a” is an array with value 10 and 20. See below commands to print keys, key value
pairs and values of array.
puts [array get a] -> To print key value pairs we use this command
1 10 2 20
puts [array names a] -> To print only keys
12
puts $a(1) -> To print first value of array
10
puts $a(2) -> To print second value of array
20
For print “Nth” value of array a, we will use Puts $a(N)
Items of data passed to a script from the command line are known as arguments. The
number of command line arguments to a Tcl script is passed as the global variable argc .
The name of a Tcl script is passed to the script as the global variable argv0 , and the rest
of the command line arguments are passed as a list in argv.
Output
Arithmetic Operator
set a 20
set b 10
puts [expr $a - $b]
10
*Multiply two or more operands
set a 20
set b 10
puts [expr $a * $b]
200
/ Divide numerator by denumerator
set a 20
set b 10
puts [expr $a / $b]
2
% Modulus operator divides numerator by de-numerator but returns reminder
set a 20
set b 10
puts [expr $a % $b]
0
Relational Operator
Checks if the value of left operand is greater than the value of the right operand. If yes,
then condition becomes true and return 1 else return 0.
set a 20
set b 10
puts [expr $a > $b]
1
Check if the value of left operand is less than the value of the right operand. If yes, then
condition becomes true and return 1 else return 0
set a 10
set b 20
puts [expr $a < $b]
1
>= Checks if the value of left operand is greater than or equal to the value of right
operand, if yes then condition becomes true and return 1 else return 0
set a 20
set b 10
puts [expr $a >= $b]
1
<= Checks if the value of left operand is less than or equal to the value of right operand,
if yes then condition becomes true and return 1 else return 0
set a 20
set b 10
puts [expr $a <= $b]
0
!= Checks if the values of two operands are equal or not, if values are not equal then
condition becomes true and return 1 else return 0
set a 20
set b 10
puts [expr $a != $b]
1
== Checks if the values of two operands are equal or not, if yes then condition becomes
true and return 1 else return 0
set a 20
set b 10
puts [expr $a == $b]
0
Logical Operator
&& If both the operands are non-zero, then condition becomes true and return 1 else
return 0
set a 20
set b 10
puts [expr $a && $b]
1
|| If any of the two operands is non-zero, then condition becomes true and return 1 else
return 0
set a 0
set b 10
puts [expr $a || $b]
1
! Used to reverse the result of any expression. Here in the output, you can see the value
of 'a' has now become 1 from 0. While the value of 'b' has become 0 from 1.
set a 0
set b 1
puts [expr !$a]
1
puts [expr !$b]
0
Bitwise Operator
& (bitwise and) perform bit by bit operation and follow the below table for operation.
A B A&B
0 0 0
0 1 0
1 1 1
1 0 0
Ex:
set A 10
set B 20
| (bitwise or) perform bit by bit operation and follow the below table
A B A|B
0 0 0
0 1 1
1 1 1
1 0 1
Ex:
set A 10
set B 20
A | B will be 0 0 0 1 1 1 1 0
^ (bitwise exclusive or) perform bit by bit operation and follow the below table
A B A^B
0 0 0
0 1 1
1 1 0
1 0 1
Ex:
set A 10
set B 20
0 1
1 0
set A 7
puts [expr ~$A]
-8
Ternary Operator ( ?:)
Syntax is
If condition-exp is true, exp1 is evaluated and the result is returned. If the cond-exp is
false, exp2 is evaluated and its result is returned. In our example, exp1 is true as the value
of A is greater than 6.
set A 7
set result [expr $A > 6 ? true : false]
puts $result
true
Shift Operator
Shift operator is denoted by either << left shift operator, or by the >> right shift
operator. For << left shift operator, the left operands value is moved left by the number
of bits specified by the right operand.
set A 7
set result [expr $A << 2]
puts $result
For the >> right shift operator, the left operands value is moved right by the number of
bits specified by the right operand.
set A 7
set result [expr $A >> 2]
puts $result
String comparison operator compares the value of both operands. If the value of operand
are same, then it will return 1 else return 0. In example value for both A and B is 7,
therefore result return 1.
set A 7
set B 7
set result [expr $A eq $B]
puts $result
1
Ne (if value of both operand are different then it will return 1 else return 0)
set A 7
set B 8
set result [expr $A ne $B]
puts $result
1
Exponentiation operator
set A 7
set result [expr $A ** 2]
puts $result
49
List Operator
If the required value found in the defined list, it returns 1 else return 0. In example value
1 exists in variable 'a' hence it will return 1.
set a {1 2 3}
if {1 in $a} {
puts "ok"
} else {
puts "fail"
}
Output: ok
ni, if the required value found in the defined list then it will return 0 else return 1.
set a {1 2 3}
if {1 ni $a} {
puts "ok"
} else {
puts "fail"
}
Output: fail
TCL flow control and decision making
There are various flow control and decision making command which are used to alter
the flow of a program. Program executions always start from the top of source file to the
bottom.
If ... statement
Syntax
if expr ?then? body
set age 10
If expression is evaluated to true, then it will return body_1 else it will return body_2
set age 10
if {$age < 20} {
puts "Age is less than 20"
} else {
Puts "Age is greater than 20"
}
output: Age is less than 20
Nested if..else statement
It means one if or else..if statement can be put inside another if or else..if statements.
Syntax
If {expression_1} {
Body_1
If {expression_2} {
Body_2
}
}
Ex:
set a 10
set b 20
if {$a == 10} {
# if expression_1 is true then it will go to expression_2
if {$b == 20} {
#if expression_2 is true then it will print the below string
puts "value of a is 10 and b is 20"
}
}
The switch statement enables a variable to be tested for equality against a list of values.
It evaluates the list of values and returns the result of that evaluation. If no values
matches then default values will be returned.
Example:
#!/usr/bin/tclsh
# switch_cmd.tcl
set domain x
switch $domain {
x { puts "x" }
y { puts "y" }
z { puts "z" }
default { puts "unknown" }
}
Nested switch
Nested switch statement means switch statement inside a switch statement.
Syntax :
switch <switchingstring1> {
<matchstring1> {
body1
switch <switchingstring2> {
<matchstring2> {
body2
}
...
switch <switchingstringN> {
<matchStringN> {
bodyN
}
}
}
Example: In the following example, value of a is 100, and with the same code we switch
statement for another value of b is 200. The out will show value for both a and b.
#!/usr/bin/tclsh
set a 100
set b 200
switch $a {
100 {
puts "The value of a is $a"
switch $b {
200 {
puts "The value of b is $b"
}
}
}
}
Output:
While command
When a given condition is true then a statement or group of statement repeats which are
in the loop body.
Syntax:
While {condition} {
Statements
}
Ex :
#!/usr/bin/tclsh
Set a 10
While {$a < 12} {
Puts "a is $a"
incr a
}
Output
a is 10
a is 11
In the above example, "incr" built-in command is used. It means the value of 'a' will be
increased by 1 till the maximum value (<12).
For command
It executes a sequence of statements multiple times based upon a counter value. It is
automatically increased or decreased during each repetition of the loop.
Syntax
For {start} {test} {next} {
Body
}
Example: In below example value of 'i' is set to 0 and incremented till value <4.
#!/usr/bin/tclsh
for {set i 0} {$i < 4} {incr i} {
put $i
}
Output
0
1
2
3
Tcl Data Structures are:
Arrays.
Namespaces.
Procedures.
Interpreters.
Dictionaries.
Arrays:
An array is a systematic arrangement of a group of elements using indices. The syntax
for the conventional array is shown below.
set ArrayName(Index) value
An example for creating simple array is shown below.
#!/usr/bin/tclsh
set languages(0) Tcl
set languages(1) “C Language”
puts $languages(0)
puts $languages(1)
When the above code is executed, it produces the following result
Tcl
C Language
Size of Array
The syntax for calculating size array is shown below.
[array size variablename]
An example for printing the size is shown below.
#!/usr/bin/tclsh
set languages(0) Tcl
set languages(1) “C Language”
puts [array size languages]
When the above code is executed, it produces the following result
2
Array Iteration
Though, array indices can be non-continuous like values specified for index 1 then index
10 and so on. But, in case they are continuous, we can use array iteration to access
elements of the array. Simple array iteration for printing elements of the array is shown
below.
#!usr/bin/tclsh
set languages(0) Tcl
set languages(1) “C Language”
for {set index 0} {$index<[array size languages]} {incr index} {
puts “languages($index) : $languages($index)”
}
When the above code is executed, it produces the following result
languages(0) : Tcl
languages(1) : C Language
Namespaces:
Namespace is a container for set of identifiers that is used to group variables and
procedures. Namespaces are available from Tcl version 8.0. Before the introduction of
the namespaces, there was single global scope. Now with namespaces, we have
additional partitions of global scope.
Creating Namespace
Namespaces are created using the namespace command. A simple example for creating
namespace is shown below
#!/usr/bin/tclsh
namespace eval MyMath {
#Create a variable inside the namespace
variable myResult
}
#Create procedures inside the namespace
proc MyMath::Add {a b } {
set MyMath::myResult [expr $a+$b]
}
MyMath::Add 10 23
puts $::MyMath::myResult
When the above code is executed, it produces the following result
33
In the above program, you can see there is a namespace with a variable myResult and a
procedure Add. This makes it possible to create variables and procedures with the same
names under different namespaces.
Nested Namespaces
Tcl allows nesting of namespaces. A simple example for nesting namespaces is given
below
#!/usr/bin/tclsh
namespace eval MyMath {
#Create a variable inside the namespace
variable myResult
}
namespace eval extendedMath{
# Create a variable inside the namespace
namespace eval MyMath {
#Create a variable inside the namespace
variable myResult
}
set::MyMath::myResult “test1”
puts $::MyMath::myResult
set::extendedMath::MyMath::myResult “test2”
puts $::extendedMath::MyMath::myResult
Trapping errors:
Error handling in Tcl is provided with the help of error and catch commands. The
syntax for each of these commands is shown below.
Error syntax:
In the above catch command syntax, script is the code to be executed, resultVarName is
variable that holds the error or the result. The catch command returns 0 if there is no
error, and 1 if there is an error.
An example for simple error handling is shown below
#!/usr/bin/tclsh
proc Div {a b} {
if {b == 0} {
error “Error generated by error” “Info String for error” 401
} else {
return [expr $a/$b]
}
}
if {[catch {puts “Result = [Div 10 0]”} errmsg]} {
puts “ErrorMsg: $errmsg”
puts “ErrorCode: $errorCode”
puts “ErrorInfo” \n&errorInfo\n”
}
if {[catch {puts “Result = [Div 10 2]”} errmsg]} {
puts “ErrorMsg: $errmsg”
puts “ErrorCode: $errorCode”
puts “ErrorInfo” \n&errorInfo\n”
}
When the above code is executed, it produces the following result
ErrorMsg: Error generated by error
ErrorCode: 401
ErrorInfo:
Info String for error
(procedure "Div" line 1)
invoked from within
"Div 10 0"
Result = 5
As you can see in the above example, we can create our own custom error messages.
Similarly, it is possible to catch the error generated by Tcl. An example is shown below
#!/usr/bin/tclsh
catch {set file [open [Link]]} result
puts “ErrorMsg: $result”
puts “ErrorCode: $errorCode”
puts “ErrorInfo:\n$errorInfo\n”
Strings:
The primitive data-type of Tcl is string and often we can find quotes on Tcl as string
only language. These strings can contain alphanumeric character, just numbers, Boolean,
or even binary data. Tcl uses 16 bit unicode characters and alphanumeric characters can
contain letters including non-Latin characters, number or punctuation.
Boolean value can be represented as 1, yes or true for true and 0, no, or false for false.
String Representations
Unlike other languages, in Tcl, you need not include double quotes when it's only a single
word. An example can be
#!/usr/bin/tclsh
set myVariable hello
puts $myVariable
When the above code is executed, it produces the following result
hello
When we want to represent multiple strings, we can use either double quotes or curly
braces. It is shown below
#!/usr/bin/tclsh
set myVariable “hello world”
puts $myVariable
set myVariable {hello world}
puts $myVariable
When the above code is executed, it produces the following result
hello world
hello world
String Escape Sequence
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').
There are certain characters in Tcl when they are preceded by a backslash they will have
special meaning and they are used to represent like newline (\n) or tab (\t). Here, you
have a list of some of such escape sequence codes
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
String Command
The list of subcommands for string command is listed in the following table
[Link]. Methods & Description
5 length string
Returns the length of string.
8 tolower string
Returns the lowercase string.
9 toupper string
Returns the uppercase string.
trim string ?trimcharacters?
10
Removes trimcharacters in both ends of string. The default trimcharacters is
whitespace.
Examples of some commonly used Tcl string sub commands are given below.
String Comparison
When the above code is compiled and executed, it produces the following result
Index of String
When the above code is compiled and executed, it produces the following result
Length of String
When the above code is compiled and executed, it produces the following result
Handling Cases
When the above code is compiled and executed, it produces the following result
Trimming Characters
When the above code is compiled and executed, it produces the following result
Matching Strings
When the above code is compiled and executed, it produces the following result
Append Command
set s1 Hello
append s1 “ World”
puts $s1
When the above code is compiled and executed, it produces the following result
Hello "World"
Format command
The following table shows the list of format specifiers available in Tcl
Specifier Use
%s String representation
%d Integer representation
Files
Tcl supports file handling with the help of the built in commands open, read, puts, gets,
and close.
A file represents a sequence of bytes, does not matter if it is a text file or binary file.
Opening Files
Tcl uses the open command to open files in Tcl. The syntax for opening a file is as
follows
open fileName accessMode
Here, filename is string literal, which you will use to name your file
and accessMode can have one of the following values −
R
1
Opens an existing text file for reading purpose and the file must exist. This is
the default mode used when no accessMode is specified.
W
2
Opens a text file for writing, if it does not exist, then a new file is created else
existing file is truncated.
A
3
Opens a text file for writing in appending mode and file must exist. Here, your
program will start appending content in the existing file content.
4 r+
Opens a text file for reading and writing both. File must exist already.
w+
5
Opens a text file for reading and writing both. It first truncate the file to zero
length if it exists otherwise create the file if it does not exist.
a+
6 Opens a text file for reading and writing both. It creates the file if it does not
exist. The reading will start from the beginning, but writing can only be
appended.
Closing a File
To close a file, use the close command. The syntax for close is as follows
close fileName
Any file that has been opened by a program must be closed when the program finishes
using that file. In most cases, the files need not be closed explicitly; they are closed
automatically when File objects are terminated automatically.
Writing a File
Puts command is used to write to an open file.
puts $filename "text to write"
A simple example for writing to a file is shown below.
#!/usr/bin/tclsh
set fp [open “[Link]” w+]
puts $fp “test”
close $fp
When the above code is compiled and executed, it creates a new file [Link] in the
directory that it has been started under (in the program's working directory).
Reading a File
Following is the simple command to read from a file
set file_data [read $fp]
A complete example of read and write is shown below
#!/usr/bin/tclsh
set fp [open “[Link]” w+]
puts $fp “test”
close %fp
set fp [open “[Link]” r]
set file_data [read $fp]
puts $file_data
close $fp
When the above code is compiled and executed, it reads the file created in previous
section and produces the following result
test
Here is another example for reading file till end of file line by line
#!/usr/bin/tclsh
set fp[open “[Link]” w+]
puts $fp “test\ntest”
close %fp
set fp[open “[Link]” r]
while { [gets $fp data]>=0} {
puts $data
}
Close $fp
When the above code is compiled and executed, it reads the file created in previous
section and produces the following result
test
test
• GUI events - Tk's raison d'etre. Note that this includes send and
various wm subcommands as well as bind and the -command options to various
widgets...
• File events - These occur when it becomes possible to either read from or write to
a channel (especially to a pipe, socket or serial port.)
• Timer events - Great for scheduling things for happening later, and brilliant for
use with periodic activity.
• Idle events - Useful for when you wish to put something off until there is nothing
to do except wait for events (mainly used in the management of display updates...)
• Virtual events - Comes in handy when a certain program state which is reached
should call a proc at a higher abstraction level of the application program. It is not
good practice to call a high level proc from a lower level. event generate is helpful
because (a) the programmer specifies a name for the virtual event (hence a low
level software module is consistent in having defined names for ALL internal
resources which can be used by apps) and (b) the event can simply be ignored
when not needed.
The public Internet is a worldwide computer network, that is, a network that
interconnects millions of computing devices throughout the world.
Different links can transmit data at different rates, with the transmission
rate of a link measured in bits/second.
Packet switches come in many shapes and flavors, but two most prominent
types in today's Internet are routers and link-layer switches. Both types of
switches forward packets toward their ultimate destinations.
From the sending end system to the receiving end system, the sequence of
communication links and packet switches traversed by a packet is known as
a route or path through the network. Rather than provide a dedicated path
between communicating end systems, the Internet uses a technique known
as packet switching that allows multiple communicating end systems to share
a path, or parts of a path, at the same time.
Security Issues
The application provides a security model that restricts the execution of the applet. For
example, the application might be a Web browser and the applet might be a program that
animates the content of a Web page. Or, an application might consist of only a security
model with no other functionality, and it might be used to run large “applets” that
implement major applications such as spreadsheets or word processors.
The security issues associated with applets fall into three major groups: integrity attacks,
privacy attacks, and denial of service attacks. These are discussed individually in the
subsections below, followed by a discussion of risk management in general.
Integrity attacks
Privacy attacks
The second form of attack consists of information theft or leakage: a malicious applet
may try to read private information from the host environment and transmit it to a
conspirator outside the environment. Information disclosed in this way may have direct
value to the recipient, such as business information that could affect the price of a
company’s stock, or its disclosure could damage the party from which it was taken, for
example, if it describes an individual’s treatment for substance abuse. One approach to
the privacy problem is to prevent applets from accessing sensitive information at all.
However, this approach would also prevent applets from performing many useful
functions. For example, this approach would prevent applets from helping to display,
analyze, and edit sensitive information. A more desirable approach is to give applets
access to sensitive information but prevent them from transmitting the information
outside the host environment. This approach is called flow control.
In principle, it might seem possible for the security model to analyze the flow of
information through the applet and prevent information read from sensitive sources from
being written to insecure I/O ports. This might be done by analyzing the application
statically to detect illegal flows. Or, it might be done using a technique called data
tainting , in which data is tagged with information about its sensitivity.
Data read from a sensitive source is tagged with a high sensitivity level, and attempts to
write that data to an insecure I/O port are denied. Unfortunately, these forms of flow
control are hard to implement and use.
Denial of service
The third form of attack consists of denial of service, where the applet attempts to
interfere with the normal operation of the host system. For example, it might consume
all the available file space, cover the screen with windows so that the user cannot interact
with any other applications, or exercise a bug to crash its application.
Denial-of-service attacks are less severe from a security standpoint than integrity or
privacy attacks, yet they are harder to prevent.
They are less severe because they don’t do lasting damage; in the worst case, the effects
can be eliminated by killing the application and freeing any extraneous resources that it
allocated.
Managing risk
It is unlikely that any security policy can completely eliminate all security threats. For
example, any bug in an application gives a malicious applet the opportunity to deny
service by crashing the application. In addition, there exist subtle techniques for
signaling information that make it nearly impossible to implement perfect flow control
for privacy.
Attempts to completely eliminate the risks would restrict applets to such a degree that
they would not be able to perform any useful functions. Thus, security models like Safe-
Tcl do not try to eliminate security risks entirely.
Instead, they attempt to reduce the risks to a manageable level, so that the benefits
provided by applets are greater than the costs incurred by security attacks.
C Interface
Introduction. The Tcl API (also called' Tcl library' or' Tcl C interface') is a huge set of C
functions which can be used to create binary extensions to the Tcl language. The
functions cover the whole range of Tcl and are, if used right, platform-independent.
The file tcl.h should be considered a public declaration of the Tcl C functions,
defines/macros, and structures which a developer can safely depend on. Most of the
actual function declarations are found in the tclDecls.h file; this has to do with
the Stubs mechanism.
Tk-Visual Kits
Tk refers to Toolkit and it provides cross platform GUI widgets, which helps you in
building a Graphical User Interface. It was developed as an extension to Tcl scripting
language by John Ousterhout. Tk remained in development independently from Tcl with
version being different to each other, before, it was made in sync with Tcl in v8.0.
Features of Tk
It is cross platform with support for Linux, Mac OS, Unix, and Microsoft Windows
operating systems.
• It is an open source.
• It provides high level of extendibility.
• It is customizable.
• It is configurable.
• It provides a large number of widgets.
• It can be used with other dynamic languages and not just Tcl.
• GUI looks identical across platforms.
Applications Built in Tk
Large successful applications have been built in Tcl/Tk.
• Dashboard Soft User Interface
• Forms GUI for Relational DB
• Ad Hoc GUI for Relational DB
• Software/Hardware System Design
• Xtask - Task Management
• Musicology with Tcl and Tk
• Calender app
• Tk mail
• Tk Debugger
Fundamental Concepts of Tk
Tk adds about 35 Tcl commands that let you create and manipulate widgets in a graphical
user interface.
Tk works with the X window system, Windows, and Macintosh. The same script can run
unchanged on all of these major platforms.
Tk also has a general-purpose drawing widget called a canvas that lets you create lighter-
weight items such as lines, boxes, and bitmaps.
Just as a hierarchical file system has directories (i.e., folders) that are containers for files
and directories, a hierarchical window system uses windows as containers for other
windows.
Widgets are under the control of a geometry manager that controls their size and location
on the screen.
Until a geometry manager learns about a widget, it will not be mapped onto the screen
and you will not see it.
Tk has powerful geometry managers that make it very easy to create nice screen layouts.
The main trick with any geometry manager is that you use frame widgets as containers
for other widgets. One or more widgets are created and then arranged in a frame by a
geometry manager.
By putting frames within frames you can create complex layouts. There are three
different geometry managers you can use in Tk: grid, pack, and place.
Tk by example
Button
A button is a widget that is typically used by a GUI programmer to receive a simple
command from the user - a "press here to submit" type idea is typically represented by a
button.
#! /usr/bin/tclsh
package require Tk
option add *[Link] 0 ;# to make it look better on Windows
option add *[Link] 1
#---------------------------------------------------- testing i18n
package require msgcat
namespace import msgcat::mc msgcat::mcset
mcset de Start Los
mcset de Stop Halt
mcset de Zero Null
mcset fr Start Allez
mcset fr Stop Arrêtez
mcset fr Zero ???
mcset zh Start \u8DD1
mcset zh Stop \u505C
mcset zh Zero ???
msgcat::mclocale en ;# edit this line for display language
#--------------------------------------------------------------- UI
button .start -text [mc Start] -command Start
label .time -textvar time -width 9 -bg black -fg yellow -font "Sans 20"
set time 00:00.00
button .stop -text [mc Stop] -command Stop
button .zero -text [mc Zero] -command Zero
set state 0
bind . <Key-space> {
if {$state} {.stop invoke
} else {
.start invoke
}
}
bind . <Key-0> {
.zero invoke
}
eval pack [winfo children .] -side left -fill y
#------------------------------------------------------- procedures
proc every {ms body} {eval $body; after $ms [namespace code [info level 0]]}
proc Start {} {
if {$::time eq {00:00.00}} {
set ::time0 [clock clicks -milliseconds]
}
every 20 {
set m [expr {[clock clicks -milliseconds] - $::time0}]
set ::time [format %2.2d:%2.2d.%2.2d \
[expr {$m/60000}] [expr {($m/1000)%60}] [expr {$m%1000/10}]]
incr ::titleskip
if {$::titleskip >= 12} {
wm title . "Timer $::time"
set ::titleskip 0
}
}
.start config -state disabled
set ::state 1
}
proc Stop {} {
if {[llength [after info]]} {
after cancel [after info]
}
.start config -state normal
set ::state 0
}
proc Zero {} {
set ::time 00:00.00
set ::time0 [clock clicks -milliseconds]
}