Sei sulla pagina 1di 139

5/22/2016

TclTkQuickGuide

TclTkQuickGuide
Advertisements

PreviousPage

NextPage

TclOverview
TclisshortenedformofToolCommandLanguage.JohnOusterhoutoftheUniversityof
California, Berkeley, designed it. It is a combination of a scripting language and its
owninterpreterthatgetsembeddedtotheapplicationwedevelopwithit.
Tcl was developed initially for Unix. It was then ported to Windows, DOS, OS/2 and
MacOSX.TclismuchsimilartootherunixshelllanguageslikeBourneShell(Sh),the
CShell(csh),theKornShell(sh),andPerl.
Itaimsatprovidingabilityforprogramstointeractwithotherprogramsandalsofor
acting as an embeddable interpreter. Even though, the original aim was to enable
programstointeract,youcanfindfullfledgedapplicationswritteninTcl/Tk.

FeaturesofTcl
ThefeaturesofTCLareasfollows:
Reduceddevelopmenttime.
PowerfulandsimpleuserinterfacekitwithintegrationofTK.
Write once, run anywhere. It runs on Windows, Mac OS X and almost every
Unixplatform.
Quiteeasytogetstartedforexperiencedprogrammerssincethelanguageis
sosimplethattheycanlearnTclinfewhoursordays.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

1/139

5/22/2016

TclTkQuickGuide

You can easily extend existing applications with Tcl. Also, it is possible to
includeTclinC,C++orJavatoTclorviceversa.
Haveapowerfulsetofnetworkingfunctions.
Finally, its open source, free and can be used for commercial applications
withoutanylimit.

Applications
TclisageneralpurposelanguageandyoucanfindTcleverywhere.Itincludes,
Scalablewebsitesthatareoftenbackedbydatabases.
HighperformancewebserversbuildwithTclHttpd.
TclwithCGIbasedwebsites.
DesktopGUIapplications.
Embeddedapplications.

TclEnvironmentSetup
TryitOption
You really do not need to set up your own environment to start learning Tcl
programming. Reason is very simple, we already have set up Tcl Programming
environmentonline,sothatyoucanexecutealltheTclexamplesonlineatthesame
timewhenyouaredoingyourtheorywork.Thisgivesyouconfidenceinwhatyouare
readingandtochecktheresultwithdifferentoptions.Feelfreetomodifyanyexample
andexecuteitonline.
TryfollowingexampleusingTryitoptionavailableatthetoprightcornerofthebelow
samplecodebox:
#!/usr/bin/tclsh
puts"Hello,World!"

FormostoftheTclexamplesgiveninthistutorial,youwillfindTryitoption,sojust
make use of it and enjoy your learning. For Tk examples you will need to have a
consoletoseegraphicalresultssowerecommendtohaveyourownTksetup.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

2/139

5/22/2016

TclTkQuickGuide

LocalEnvironmentSetup
If you are willing to set up your environment for Tcl, you need the following two
softwaresapplicationsavailableonyourcomputer,(a)TextEditor,(b)TclInterpreter.

TextEditor
This will be used to type your program. Examples of few editors include Windows
Notepad,OSEditcommand,Brief,Epsilon,EMACS,andvimorvi.
Name and version of text editor can vary on different operating systems. For
example,NotepadwillbeusedonWindows,andvimorvicanbeusedonwindowsas
wellasLinuxorUNIX.
The files you create with your editor are called source files and contain program
sourcecode.ThesourcefilesforTclprogramsarenamedwiththeextension".tcl".
Beforestartingyourprogramming,makesureyouhaveonetexteditorinplaceand
youhaveenoughexperiencetowriteacomputerprogram,saveitinafile,builditand
finallyexecuteit.

TheTclInterpreter
It is just a small program that enables you to type Tcl commands and have them
executed line by line. It stops execution of a tcl file in case it encounters an error
unlikeacompilerthatexecutesfully.
LetshaveahelloWorld.tclfileasfollows.Wewillusethisasfirstprogramwerunon
platformyouchoose.
#!/usr/bin/tclsh
puts"HelloWorld!"

InstallationonWindows
Downloadthelatestversionforwindowsinstaller

fromthelistofActiveTclbinaries

available.ActiveTclcommunityeditionisfreeforpersonaluse.
RunthedownloadedexecutabletoinstalltheTclwhichcanbedonebyfollowingthe
onscreeninstructions.
NowwecanbuildandrunaTclfilesayhelloWorld.tclbyswitchingtofoldercontaining
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

3/139

5/22/2016

TclTkQuickGuide

thefileusingcdcommandandthenexecutetheprogramusingthefollowingsteps
C:\Tcl>tclshhelloWorld.tcl

Wecanseethefollowingoutput.
C:\Tcl>helloWorld

C:\Tclisthefolder,Iamusingtosavemysamples.Youcanchangeittothefolderin
whichyouhavesavedTclprograms.

InstallationonLinux
Most Linux operating systems comes with Tcl inbuilt and you can get started right
awayinthosesystems.Incase,itsnotavailable,youcanusethefollowingcommand
todownloadandinstallTclTk.
$yuminstalltcltk

NowwecanbuildandrunaTclfilesayhelloWorld.tclbyswitchingtofoldercontaining
thefileusingcdcommandandthenexecutetheprogramusingthefollowingsteps
$tclshhelloWorld.tcl

Wecanseethefollowingoutput.
$helloworld

InstallationonDebianbasedsystems
Incase,itsnotavailableinyourOS,youcanusethefollowingcommandtodownload
andinstallTclTk.
$sudoaptgetinstalltcltk

NowwecanbuildandrunaTclfilesayhelloWorld.tclbyswitchingtofoldercontaining
thefileusingcdcommandandthenexecutetheprogramusingthefollowingsteps
$tclshhelloWorld.tcl

Wecanseethefollowingoutput.
$helloworld

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

4/139

5/22/2016

TclTkQuickGuide

InstallationonMacOSX
Download the latest version for Mac OS X package

from the list of Active Tcl

binariesavailable.ActiveTclcommunityeditionisfreeforpersonaluse.
RunthedownloadedexecutabletoinstalltheActiveTclwhichcanbedonebyfollowing
theonscreenintsructions.
NowwecanbuildandrunaTclfilesayhelloWorld.tclbyswitchingtofoldercontaining
thefileusingcdandthenexecutetheprogramusingthefollowingsteps
$tclshhelloWorld.tcl

Wecanseethefollowingoutput.
$helloworld

Installationfromsourcefiles
You can use the option of installing from source files when a binary package is not
available.ItisgenerallypreferredtouseTclbinariesforWindowsandMacOSX,so
onlycompilationofsourcesonunixbasedsystemisshownbelow.
Downloadthesourcefiles.
Nowusethefollowingcommandstoextract,compileandbuildafterswitching
tothedownloadedfolder.
$tarzxftcl8.6.1src.tar.gz
$cdtcl8.6.1
$cdunix
$./configureprefix=/optenablegcc
$make
$sudomakeinstall

Note : Make sure, you change the file name to the version you downloaded on
commands1and2intheabove.

TclSpecialVariables
In Tcl, we classify some of the variables as special variables and they have a
predefinedusage/functionality.Thelistofspecialsvariablesislistedbelow.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

5/139

5/22/2016

TclTkQuickGuide

SpecialVariable

Description

argc

Referstonumberofcommandlinearguments.

argv

Referstothelistcontainingthecommandlinearguments.

argv0

Referstothefilenameofthefilebeinginterpretedorthenameby
whichweinvokethescript.

env

Usedforrepresentingthearrayofelementsthatareenvironmental
variables.

errorCode

ProvidestheerrorcodeforlastTclerror.

errorInfo

ProvidesthestacktraceforlastTclerror.

tcl_interactive

Usedtoswitchbetweeninteractiveandnoninteractivemodesby
settingthisto1and0respectively.

tcl_library

UsedforsettingthelocationofstandardTcllibraries.

tcl_pkgPath

Providesthelistofdirectorieswherepackagesaregenerallyinstalled.

tcl_patchLevel

ReferstothecurrentpatchleveloftheTclinterpreter.

tcl_platform

Usedforrepresentingthearrayofelementswithobjectsincluding
byteOrder,machine,osVersion,platform,andos.

tcl_precision

Referstotheprecisioni.e.numberofdigitstoretainwhen
convertingtofloatingpointnumberstostrings.Thedefaultvalueis
12.

tcl_prompt1

Referstotheprimaryprompt.

tcl_prompt2

Referstothesecondarypromptwithinvalidcommands.

tcl_rcFileName

Providestheuserspecificstartupfile.

tcl_traceCompile

Usedforcontrollingthetracingofbytecodecompilation.Use0forno
output,1forsummary,and2fordetailed.

tcl_traceExec

Usedforcontrollingthetracingofbytecodeexecution.Use0forno
output,1forsummary,and2fordetailed.

tcl_version

ReturnsthecurrentversionoftheTclinterpreter.

TheabovespecialvariableshavetheirspecialmeaningsfortheTclinterpreter.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

6/139

5/22/2016

TclTkQuickGuide

ExamplesforusingTclspecialvariables
Let'sseesomeexamplesforspecialvariables.

Tclversion
#!/usr/bin/tclsh
puts$tcl_version

Whenyouruntheprogram,youwillgetasimilaroutputasshownbelow.
8.5

TclEnvironmentPath
#!/usr/bin/tclsh
puts$env(PATH)

Whenyouruntheprogram,youwillgetasimilaroutputasshownbelow.

/web/com/GNUstep/Tools:/usr/GNUstep/Local/Tools:/usr/GNUstep/System/Tools:/usr/local/sml/bin:/usr/local/fle

TclPackagePath
#!/usr/bin/tclsh
puts$tcl_pkgPath

Whenyouruntheprogram,youwillgetasimilaroutputasshownbelow.
/usr/lib64/tcl8.5/usr/share/tcl8.5/usr/lib64/tk8.5/usr/share/tk8.5

TclLibrary
#!/usr/bin/tclsh
puts$tcl_library

Whenyouruntheprogram,youwillgetasimilaroutputasshownbelow.
/usr/share/tcl8.5

TclPatchlevel
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

7/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
puts$tcl_patchLevel

Whenyouruntheprogram,youwillgetasimilaroutputasshownbelow.
8.5.7

TclPrecision
#!/usr/bin/tclsh
puts$tcl_precision

Whenyouruntheprogram,youwillgetasimilaroutputasshownbelow.
0

TclStartupFile
#!/usr/bin/tclsh
puts$tcl_rcFileName

Whenyouruntheprogram,youwillgetasimilaroutputasshownbelow.
~/.tclshrc

TclBasicSyntax
Tclisquitesimpletolearnandlet'sstartcreatingourfirstTclprogram!

FirstTclProgram
Let us write a simple Tcl program. All Tcl files will have extension .tcl. So put the
followingsourcecodeinatest.tclfile.
#!/usr/bin/tclsh
puts"Hello,World!"

Assuming,Tclenvironmentissetupcorrectlylet'sruntheprogramafterswitchingto
file'sdirectoryandthenexecutetheprogramusing:
$tclshtest.tcl

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

8/139

5/22/2016

TclTkQuickGuide

Wewillgetthefollowingoutput.
Hello,World!

Let us now see the basic structure of Tcl program, so that it will be easy for you to
understand basic building blocks of the Tcl language. In Tcl, we use new line or
semicolon to terminate the previous line of code. But semicolon is not necessary, if
youareusingnewlineforeachcommand.

Comments
CommentsarelikehelpingtextinyourTclprogramandtheinterpreterignoresthem.
Commentscanbewrittenusingahash_(#)signinbeginning.
#!/usr/bin/tclsh
#myfirstprograminTcl
puts"HelloWorld!"

Multilineorblockcommentiswrittenusingifwithcondition0.Anexampleisshown
below.
#!/usr/bin/tclsh
if0{
myfirstprograminTclprogram
Itsverysimple
}
puts"HelloWorld!"

Inlinecommentsuse#.Anexampleisgivenbelow.
#!/usr/bin/tclsh
puts"HelloWorld!";#myfirstprintinTclprogram

Identifiers
A Tcl identifier is a name used to identify a variable, function, or any other user
defined item. An identifier starts with a letter A to Z or a to z or an underscore (_)
followedbyzeroormoreletters,underscores,dollars($)anddigits(0to9).
Tcldoesnotallowpunctuationcharacterssuchas@,and%withinidentifiers.Tclisa
case sensitive_ language. Thus Manpower and manpower are two different
identifiersinTcl.Herearesomeexamplesofacceptableidentifiers:
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

9/139

5/22/2016

TclTkQuickGuide

mohdzaraabcmove_namea_123
myname50_tempja23b9retVal

ReservedWords
ThefollowinglistshowsfewofthereservedwordsinTcl.Thesereservedwordsmay
notbeusedasconstantorvariableoranyotheridentifiernames.
after

append

array

auto_execok

auto_import

auto_load

auto_load_index

auto_qualify

binary

Bgerror

break

catch

cd

Clock

close

concat

continue

Dde

default

else

elseif

Encoding

eof

error

eval

Exec

exit

expr

fblocked

Fconfigure

fcopy

file

fileevent

Flush

for

foreach

format

Gets

glob

global

history

If

info

interp

join

Lappend

lindex

linsert

list

Llength

load

lrange

lreplace

Lsearch

lsort

namespace

open

Package

pid

pkg_mkIndex

proc

Puts

pwd

read

regexp

Regsub

rename

resource

return

Scan

seek

set

socket

Source

split

string

subst

Switch

tclLog

tell

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

10/139

5/22/2016

TclTkQuickGuide

time

Trace

unknown

unset

update

Uplevel

upvar

variable

vwait

While

WhitespaceinTcl
Alinecontainingonlywhitespace,possiblywithacomment,isknownasablankline,
andaTclinterpretertotallyignoresit.
Whitespace is the term used in Tcl to describe blanks, tabs, newline characters and
comments.Whitespaceseparatesonepartofastatementfromanotherandenables
theinterpretertoidentifywhereoneelementinastatement,suchasputs,endsand
thenextelementbegins.Therefore,inthefollowingstatement:
#!/usr/bin/tclsh
puts"HelloWorld!"

Theremustbeatleastonewhitespacecharacter(usuallyaspace)betweenputsand
"HelloWorld!"fortheinterpretertobeabletodistinguishthem.Ontheotherhand,in
thefollowingstatement
#!/usr/bin/tclsh
puts[expr3+2];#printsumofthe3and2

No whitespace characters are necessary between 3 and +, or between + and 2,


althoughyouarefreetoincludesomeifyouwishforreadabilitypurpose.

TclCommands
Asyouknow,TclisToolcommandlanguage,commandsarethemostvitalpartofthe
language. Tcl commands are built into the language with each having its own
predefined function. These commands form the reserved words of the language and
cannotbeusedforothervariablenamings.TheadvantagewiththeseTclcommandsis
that,youcandefineyourownimplementationforanyofthesecommandstoreplace
theoriginalbuiltinfunctionality.
Each of the Tcl commands validates the input and it reduces the work of the
interpreter.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

11/139

5/22/2016

TclTkQuickGuide

Tclcommandisactuallyalistofwords,withthefirstwordrepresentingthecommand
tobeexecuted.Thenextwordsrepresentthearguments.Inordertogroupwordsinto
asingleargument,weenclosemultiplewordswith""or{}.
ThesyntaxofTclcommandisasfollows.
commandNameargument1argument2...argumentN

Let'sseeansimpleexampleofTclcommand.
#!/usr/bin/tclsh
puts"Hello,world!"

Whenabovecodeisexecuted,itproducesfollowingresult.
Hello,world!

Intheabovecode,putsistheTclcommandand"HelloWorld"isargument1.Assaid
before,wehaveused""togrouptwowords.
Let'sseeanotherexampleofTclcommandwithtwoarguments.
#!/usr/bin/tclsh
putsstdout"Hello,world!"

Whenabovecodeisexecuted,itproducesfollowingresult.
Hello,world!

Intheabovecode,putsistheTclcommand,stdoutisargument1and"HelloWorld"is
argument2.Herestdoutmakestheprogramtoprintinthestandardoutputdevice.

Commandsubstitution
Incommandsubstitutions,squarebracketsareusedtoevaluatethescriptsinsidethe
squarebrackets.Asimpleexampletoaddtwonumbersisshownbelow.
#!/usr/bin/tclsh
puts[expr1+6+9]

Whenabovecodeisexecuted,itproducesfollowingresult.
16
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

12/139

5/22/2016

TclTkQuickGuide

Variablesubstitution
In variable substitutions, $ is used before the variable name and this returns the
contentsofthevariable.Asimpleexampletosetavaluetoavariableandprintitis
shownbelow.
#!/usr/bin/tclsh
seta3
puts$a

Whenabovecodeisexecuted,itproducesfollowingresult.
3

Backslashsubstitution
Thesearecommonlycalledescapesequenceswitheachbackslashfollowedbyletter
havingitsownmeaning.Asimpleexamplefornewlinesubstitutionisshownbelow.
#!/usr/bin/tclsh
puts"Hello\nWorld"

Whenabovecodeisexecuted,itproducesfollowingresult.
Hello
World

TclDataTypes
TheprimitivedatatypeofTclisstringandoftenwecanfindquotesonTclasstring
onlylanguage.Theseprimitivedatatypesinturncreatecompositedatatypesforlist
andassociativearray.InTcl,datatypescanrepresentnotonlysimpleTclobjects,but
alsocanrepresentcomplexobjectslikehandles,graphicobjects(mostlywidgets),and
I/Ochannels.Let'slookindetailabouteachoftheabove.

SimpleTclObjects
In Tcl, whether it is an integer number, boolean, floating point number, or a string.
Whenyouwanttouseavariable,youcandirectlyassignvaluetoit,thereisnostep
ofdeclarationinTcl.Therecanbeinternalrepresentationsforthesedifferenttypesof
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

13/139

5/22/2016

TclTkQuickGuide

objects. It can transform one datatype to an other when required. The syntax for
assigningvaluetovariableisasfollows.
#!/usr/bin/tclsh
setmyVariable18
puts$myVariable

Whenabovecodeisexecuted,itproducesfollowingresult.
18

TheabovestatementwillcreateavariablenamemyVariableandstoresitasastring
even though, we have not used double quotations. Now, if we try to make an
arithmeticonthevariable,itisautomaticallyturnedtoaninteger.Asimpleexample
isshownbelow.
#!/usr/bin/tclsh
setmyVariable18
puts[expr$myVariable+6+9]

Whenabovecodeisexecuted,itproducesfollowingresult.
33

Oneimportantthingtonoteisthat,thesevariablesdon'thaveanydefaultvaluesand
mustbeassignedvaluebeforetheyareused.
Ifwetrytoprintusingputs,thenumberistransformedtoproperstring.Havingtwo
representations, internal and external, help Tcl to create complex data structures
easily compared to other languages. Also, Tcl is more efficient due to its dynamic
objectnature.

Stringrepresentations
Unlike other languages, in Tcl, you need not include double quotes when it's only a
singleword.Anexamplecanbe,
#!/usr/bin/tclsh
setmyVariablehello
puts$myVariable

Whenabovecodeisexecuted,itproducesfollowingresult.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

14/139

5/22/2016

TclTkQuickGuide

hello

Whenwewanttorepresentmultiplestrings,wecanuseeitherdoublequotesorcurly
braces.Itisshownbelow.
#!/usr/bin/tclsh
setmyVariable"helloworld"
puts$myVariable
setmyVariable{helloworld}
puts$myVariable

Whenabovecodeisexecuted,itproducesfollowingresult.
helloworld
helloworld

Lists
Listisnothingbutagroupofelements.Agroupofwordseitherusingdoublequotesor
curlybracescanbeusedtorepresentasimplelist.Asimplelistisshownbelow.
#!/usr/bin/tclsh
setmyVariable{redgreenblue}
puts[lindex$myVariable2]
setmyVariable"redgreenblue"
puts[lindex$myVariable1]

Whenabovecodeisexecuted,itproducesfollowingresult.
blue
green

AssociativeArray
Associative arrays have an index (key) that is not necessarily an integer. It is
generallyastringthatactslikekeyvaluepairs.Asimpleexampleisshownbelow.
#!/usr/bin/tclsh
setmarks(english)80
puts$marks(english)
setmarks(mathematics)90
puts$marks(mathematics)

Whenabovecodeisexecuted,itproducesfollowingresult.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

15/139

5/22/2016

TclTkQuickGuide

80
90

Handles
Tcl handles are commonly used to represent files and graphics objects. These can
include handles to network requests and also other channels like serial port
communication, sockets or I/O devices. The following is an example where a file
handleiscreated.
setmyfile[open"filename"r]

YouwillseemoredetailonfilesintheTclfileI/O

chapter.

TclVariables
In Tcl, there is no concept of variable declaration. Once, a new variable name is
encountered,Tclwilldefineanewvariable.

VariableNaming
The name of variables can contain any characters and length. You can even have
whitespacesbyenclosingthevariableincurlybraces,butitisnotpreferred.
The set command is used for assigning value to a variable. The syntax for set
commandis,
setvariableNamevalue

Afewexamplesofvariablesareshownbelow.
#!/usr/bin/tclsh
setvariableA10
set{variableB}test
puts$variableA
puts${variableB}

Whenabovecodeisexecuted,itproducesfollowingresult.
10
test

Asyoucanseeintheaboveprogram,the$variableNameisusedtogetthevalueof
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

16/139

5/22/2016

TclTkQuickGuide

thevariable.

DynamicTyping
Tcl is a dynamically typed language. The value of the variable can be dynamically
convertedtotherequiredtypewhenrequired.Forexample,anumber5thatisstored
asstringwillbeconvertedtonumberwhendoinganarithmeticoperation.Itisshown
below.
#!/usr/bin/tclsh
setvariableA"10"
puts$variableA
setsum[expr$variableA+20];
puts$sum

Whenabovecodeisexecuted,itproducesfollowingresult.
10
30

Mathematicalexpressions
As you can see in the above example, expr is used for representing mathematical
expression. The default precision of Tcl is 12 digits. In order to get floating point
results,weshouldaddatleastasingledecimaldigit.Asimpleexampleexplainsthe
above.
#!/usr/bin/tclsh
setvariableA"10"
setresult[expr$variableA/9];
puts$result
setresult[expr$variableA/9.0];
puts$result
setvariableA"10.0"
setresult[expr$variableA/9];
puts$result

Whenabovecodeisexecuted,itproducesfollowingresult.
1
1.1111111111111112
1.1111111111111112

Intheaboveexample,youcanseethreecases.Inthefirstcase,thedividendandthe
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

17/139

5/22/2016

TclTkQuickGuide

divisorarewholenumbersandwegetawholenumberasresult.Inthesecondcase,
thedivisoraloneisadecimalnumberandinthethirdcase,thedividendisadecimal
number.Inbothsecondandthirdcases,wegetadecimalnumberasresult.
In the above code, you can change the precision by using tcl_precision special
variable.Itisshownbelow.
#!/usr/bin/tclsh
setvariableA"10"
settcl_precision5
setresult[expr$variableA/9.0];
puts$result

Whenabovecodeisexecuted,itproducesfollowingresult.
1.1111

TclOperators
An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. Tcl language is rich in builtin operators and provides the
followingtypesofoperators:
ArithmeticOperators
RelationalOperators
LogicalOperators
BitwiseOperators
TernaryOperator

Thistutorialwillexplainthearithmetic,relational,logical,bitwise,andotheroperators
onebyone.

ArithmeticOperators
FollowingtableshowsallthearithmeticoperatorssupportedbyTcllanguage.Assume
variableAholds10andvariableBholds20then:
ShowExamples
Operator

Description

Example

Addstwooperands

A+Bwillgive30

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

18/139

5/22/2016

TclTkQuickGuide

Subtractssecondoperandfromthefirst

ABwillgive10

Multipliesbothoperands

A*Bwillgive200

Dividesnumeratorbydenumerator

B/Awillgive2

ModulusOperatorandremainderofafteran
integerdivision

B%Awillgive0

RelationalOperators
FollowingtableshowsalltherelationaloperatorssupportedbyTcllanguage.Assume
variableAholds10andvariableBholds20,then:
ShowExamples
Operator

Description

Example

==

Checksifthevaluesoftwooperandsare
equalornot,ifyesthenconditionbecomes
true.

(A==B)isnottrue.

!=

Checksifthevaluesoftwooperandsare
equalornot,ifvaluesarenotequalthen
conditionbecomestrue.

(A!=B)istrue.

>

Checksifthevalueofleftoperandisgreater
thanthevalueofrightoperand,ifyesthen
conditionbecomestrue.

(A>B)isnottrue.

<

Checksifthevalueofleftoperandisless
thanthevalueofrightoperand,ifyesthen
conditionbecomestrue.

(A<B)istrue.

>=

Checksifthevalueofleftoperandisgreater
thanorequaltothevalueofrightoperand,
ifyesthenconditionbecomestrue.

(A>=B)isnottrue.

<=

Checksifthevalueofleftoperandisless
thanorequaltothevalueofrightoperand,
ifyesthenconditionbecomestrue.

(A<=B)istrue.

LogicalOperators
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

19/139

5/22/2016

TclTkQuickGuide

Following table shows all the logical operators supported by Tcl language. Assume
variableAholds1andvariableBholds0,then:
ShowExamples
Operator

Description

Example

&&

CalledLogicalANDoperator.Ifboththe
operandsarenonzero,thencondition
becomestrue.

(A&&B)isfalse.

||

CalledLogicalOROperator.Ifanyofthetwo
operandsisnonzero,thencondition
becomestrue.

(A||B)istrue.

CalledLogicalNOTOperator.Usetoreverses
thelogicalstateofitsoperand.Ifacondition
istruethenLogicalNOToperatorwillmake
false.

!(A&&B)istrue.

BitwiseOperators
Bitwiseoperatorworksonbitsandperformbitbybitoperation.Thetruthtablesfor&,
|,and^areasfollows:
p

p&q

p|q

p^q

AssumeifA=60andB=13nowinbinaryformattheywillbeasfollows:
A=00111100
B=00001101

A&B=00001100
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

20/139

5/22/2016

TclTkQuickGuide

A|B=00111101
A^B=00110001
The Bitwise operators supported by Tcl language are listed in the following table.
AssumevariableAholds60andvariableBholds13,then:
ShowExamples
Operator

Description

Example

&

BinaryANDOperatorcopiesabittothe
resultifitexistsinbothoperands.

(A&B)willgive12,whichis
00001100

BinaryOROperatorcopiesabitifitexistsin
eitheroperand.

(A|B)willgive61,whichis
00111101

BinaryXOROperatorcopiesthebitifitisset
inoneoperandbutnotboth.

(A^B)willgive49,whichis
00110001

<<

BinaryLeftShiftOperator.Theleftoperands
valueismovedleftbythenumberofbits
specifiedbytherightoperand.

A<<2willgive240whichis
11110000

>>

BinaryRightShiftOperator.Theleft
operandsvalueismovedrightbythe
numberofbitsspecifiedbytheright
operand.

A>>2willgive15whichis
00001111

TernaryOperator
ShowExamples
Operator

Description

Example

?:

Ternary

IfConditionistrue?ThenvalueX:OtherwisevalueY

OperatorsPrecedenceinTcl
Operatorprecedencedeterminesthegroupingoftermsinanexpression.Thisaffects
how an expression is evaluated. Certain operators have higher precedence than
others for example, the multiplication operator has higher precedence than the
additionoperator.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

21/139

5/22/2016

TclTkQuickGuide

Forexample:x=7+3*2here,xisassigned13,not20becauseoperator*has
higherprecedencethan+,soitfirstgetsmultipliedwith3*2andthenaddsinto7.
Here,operatorswiththehighestprecedenceappearatthetopofthetable,thosewith
thelowestappearatthebottom.Withinanexpression,higherprecedenceoperators
willbeevaluatedfirst.
ShowExamples
Category

Operator

Associativity

Unary

Righttoleft

Multiplicative

*/%

Lefttoright

Additive

Lefttoright

Shift

<<>>

Lefttoright

Relational

<<=>>=

Lefttoright

BitwiseAND

&

Lefttoright

BitwiseXOR

Lefttoright

BitwiseOR

Lefttoright

LogicalAND

&&

Lefttoright

LogicalOR

||

Lefttoright

Ternary

?:

Righttoleft

TclDecisions
Decision making structures require that the programmer specifies one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
otherstatementstobeexecutediftheconditionisdeterminedtobefalse.
Followingisthegeneralformofatypicaldecisionmakingstructurefoundinmostof
theprogramminglanguages:

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

22/139

5/22/2016

TclTkQuickGuide

Tcl language uses the expr command internally and hence its not required for us to
useexprstatementexplicitly.
Tcllanguageprovidesfollowingtypesofdecisionmakingstatements.
Statement

Description

ifstatement

Anifstatementconsistsofabooleanexpression
followedbyoneormorestatements.

if...elsestatement

Anifstatementcanbefollowedbyanoptionalelse
statement,whichexecuteswhenthebooleanexpression
isfalse.

nestedifstatements

Youcanuseoneiforelseifstatementinsideanotherif
orelseifstatement(s).

switchstatement

Aswitchstatementallowsavariabletobetestedfor
equalityagainstalistofvalues.

nestedswitchstatements

Youcanuseoneswitchstatementinsideanother
switchstatement(s).

TclifStatement
Anifstatementconsistsofabooleanexpressionfollowedbyoneormorestatements.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

23/139

5/22/2016

TclTkQuickGuide

Syntax
ThesyntaxofanifstatementinTcllanguageis:
if{boolean_expression}{
#statement(s)willexecuteifthebooleanexpressionistrue
}

If the boolean expression evaluates to true, then the block of code inside the if
statement will be executed. If boolean expression evaluates to false, then the first
set of code after the end of the if statement(after the closing curly brace) will be
executed.
Tcllanguageusestheexprcommandinternallyandhenceit'snotrequiredforusto
useexprstatementexplicitly.

FlowDiagram

Example
#!/usr/bin/tclsh
seta10

#checkthebooleanconditionusingifstatement
if{$a<20}{
#ifconditionistruethenprintthefollowing
puts"aislessthan20"
}
puts"valueofais:$a"

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

24/139

5/22/2016

TclTkQuickGuide

aislessthan20
valueofais:10

TclifelseStatement
Anifstatementcanbefollowedbyanoptionalelsestatement,whichexecuteswhen
thebooleanexpressionisfalse.

Syntax
Thesyntaxofanif...elsestatementinTcllanguageis:
if{boolean_expression}{
#statement(s)willexecuteifthebooleanexpressionistrue
}else{
#statement(s)willexecuteifthebooleanexpressionisfalse
}

If the boolean expression evaluates to true, then the if block of code will be
executed,otherwiseelseblockofcodewillbeexecuted.
Tcllanguageusestheexprcommandinternallyandhenceit'snotrequiredforusto
useexprstatementexplicitly.

FlowDiagram

Example

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

25/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
seta100
#checkthebooleancondition
if{$a<20}{
#ifconditionistruethenprintthefollowing
puts"aislessthan20"
}else{
#ifconditionisfalsethenprintthefollowing
puts"aisnotlessthan20"
}
puts"valueofais:$a"

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
aisnotlessthan20;
valueofais:100

Theif...elseif...elseStatement
Anifstatementcanbefollowedbyanoptionalelseif...elsestatement,whichisvery
usefultotestvariousconditionsusingsingleif...elseifstatement.

Whenusingif,elseif,elsestatementstherearefewpointstokeepinmind:
Anifcanhavezerooroneelse'sanditmustcomeafteranyelseif's.
Anifcanhavezerotomanyelseif'sandtheymustcomebeforetheelse.
Once an else if succeeds, none of the remaining else if's or else's will be
tested.

Syntax
Thesyntaxofanif...elseif...elsestatementinTcllanguageis:
if{boolean_expression1}{
#Executeswhenthebooleanexpression1istrue
}elseif{boolean_expression2}{
#Executeswhenthebooleanexpression2istrue
}elseif{boolean_expression3}{
#Executeswhenthebooleanexpression3istrue
}else{
#executeswhenthenoneoftheaboveconditionistrue
}

Example
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

26/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
seta100
#checkthebooleancondition
if{$a==10}{
#ifconditionistruethenprintthefollowing
puts"Valueofais10"
}elseif{$a==20}{
#ifelseifconditionistrue
puts"Valueofais20"
}elseif{$a==30}{
#ifelseifconditionistrue
puts"Valueofais30"
}else{
#ifnoneoftheconditionsistrue
puts"Noneofthevaluesismatching"
}
puts"Exactvalueofais:$a"

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Noneofthevaluesismatching
Exactvalueofais:100

TclNestedifStatement
ItisalwayslegalinTcltonestifelsestatements,whichmeansyoucanuseoneifor
elseifstatementinsideanotheriforelseifstatement(s).

Syntax
Thesyntaxforanestedifstatementisasfollows:
if{boolean_expression1}{
#Executeswhenthebooleanexpression1istrue
if{boolean_expression2}{
#Executeswhenthebooleanexpression2istrue
}
}

Youcannestelseif...elseinthesimilarwayasyouhavenestedifstatement.

Example

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

27/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
seta100
setb200

#checkthebooleancondition
if{$a==100}{
#ifconditionistruethencheckthefollowing
if{$b==200}{
#ifconditionistruethenprintthefollowing
puts"Valueofais100andbis200"
}
}
puts"Exactvalueofais:$a"
puts"Exactvalueofbis:$b"

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Valueofais100andbis200
Exactvalueofais:100
Exactvalueofbis:200

TclSwitchStatement
Aswitchstatementallowsavariabletobetestedforequalityagainstalistofvalues.
Each value is called a case, and the variable being switched on is checked for each
switchcase.

Syntax
ThesyntaxforunquotedswitchstatementinTcllanguageisasfollows:
switchswitchingStringmatchString1{body1}matchString2{body2}...matchStringn{bodyn}

ThesyntaxforunquotedswitchstatementinTcllanguageisasfollows:
switchswitchingString{
matchString1{
body1
}
matchString2{
body2
}
...
matchStringn{
bodyn
}
}

Thefollowingrulesapplytoaswitchstatement:
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

28/139

5/22/2016

TclTkQuickGuide

The switchingString used in a switch statement is used between the


differentblocksbycomparingtothematchString.
YoucanhaveanynumberofmatchStringblockswithinaswitch.
Aswitchstatementcanhaveanoptionaldefaultblock,whichmustappear
attheendoftheswitch.Thedefaultcasecanbeusedforperformingatask
whennoneofthecasesistrue.

FlowDiagram

Example:Unquotedversion
#!/usr/bin/tclsh
setgradeC;
switch$gradeA{puts"Welldone!"}B{puts"Excellent!"}C{puts"Youpassed!"}F{puts
puts"Yourgradeis$grade"

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Youpassed!
YourgradeisC

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

29/139

5/22/2016

TclTkQuickGuide

Example:Quotedversion
#!/usr/bin/tclsh
setgradeB;
switch$grade{
A{
puts"Welldone!"
}
B{
puts"Excellent!"
}
C{
puts"Youpassed!"
}
F{
puts"Bettertryagain"
}
default{
puts"Invalidgrade"
}
}
puts"Yourgradeis$grade"

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Welldone
YourgradeisB

TclNestedswitchStatement
Itispossibletohaveaswitchaspartofthestatementsequenceofanouterswitch.
Evenifthecaseconstantsoftheinnerandouterswitchcontaincommonvalues,no
conflictswillarise.

Syntax
Thesyntaxforanestedswitchstatementisasfollows:
switchswitchingString{
matchString1{
body1
switchswitchingString{
matchString1{
body1
}
matchString2{
body2
}
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

30/139

5/22/2016

TclTkQuickGuide

...
matchStringn{
bodyn
}
}
}
matchString2{
body2
}
...
matchStringn{
bodyn
}
}

Example
#!/usr/bin/tclsh
seta100
setb200
switch$a{
100{
puts"Thisispartofouterswitch"
switch$b{
200{
puts"Thisispartofinnerswitch!"
}

}
}
}
puts"Exactvalueofais:$a"
puts"Exactvalueofais:$b"

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Thisispartofouterswitch
Thisispartofinnerswitch!
Exactvalueofais:100
Exactvalueofais:200

The?:Operator
Wehavecoveredconditionaloperator?:inpreviouschapterwhichcanbeusedto
replaceif...elsestatements.Ithasthefollowinggeneralform:
Exp1?Exp2:Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

31/139

5/22/2016

TclTkQuickGuide

colon.
The value of a ? expression is determined like this: Exp1 is evaluated. If it is true,
thenExp2isevaluatedandbecomesthevalueoftheentire?expression.IfExp1is
false,thenExp3isevaluatedanditsvaluebecomesthevalueoftheexpression.An
exampleisshownbelow.
#!/usr/bin/tclsh
seta10;
setb[expr$a==1?20:30]
puts"Valueofbis$b\n"
setb[expr$a==10?20:30]
puts"Valueofbis$b\n"

Whenyoucompileandexecutetheaboveprogramitproducesthefollowingresult:
Valueofbis30
Valueofbis20

TclLoops
Theremaybeasituation,whenyouneedtoexecuteablockofcodeseveralnumber
oftimes.Ingeneral,statementsareexecutedsequentially:Thefirststatementina
functionisexecutedfirst,followedbythesecond,andsoon.
Programming languages provide various control structures that allow for more
complicatedexecutionpaths.
Aloopstatementallowsustoexecuteastatementorgroupofstatementsmultiple
times and following is the general form of a loop statement in most of the
programminglanguages:

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

32/139

5/22/2016

TclTkQuickGuide

Tcllanguageprovidesthefollowingtypesofloopstohandleloopingrequirements.
LoopType

Description

whileloop

Repeatsastatementorgroupofstatementswhileagivenconditionis
true.Itteststheconditionbeforeexecutingtheloopbody.

forloop

Executeasequenceofstatementsmultipletimesandabbreviatesthe
codethatmanagestheloopvariable.

nestedloops

Youcanuseoneormoreloopinsideanyanotherwhile,forordo..while
loop.

TclwhileLoop
A while loop statement in Tcl language repeatedly executes a target statement as
longasagivenconditionistrue.

Syntax
ThesyntaxofawhileloopinTcllanguageis:
while{condition}{
statement(s)
}

Here, statement(s) may be a single statement or a block of statements. The


http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

33/139

5/22/2016

TclTkQuickGuide

condition may be any expression, and true is any nonzero value. The loop iterates
whiletheconditionistrue.
When the condition becomes false, program control passes to the line immediately
followingtheloop.

FlowDiagram

Here, key point of the while loop is that the loop might not ever run. When the
conditionistestedandtheresultisfalse,theloopbodywillbeskippedandthefirst
statementafterthewhileloopwillbeexecuted.

Example
#!/usr/bin/tclsh
seta10
#whileloopexecution
while{$a<20}{
puts"valueofa:$a"
incra
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
valueofa:10
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

34/139

5/22/2016

TclTkQuickGuide

valueofa:11
valueofa:12
valueofa:13
valueofa:14
valueofa:15
valueofa:16
valueofa:17
valueofa:18
valueofa:19

TclforLoops
Aforloopisarepetitioncontrolstructurethatallowsyoutoefficientlywriteacode
thatneedstobeexecutedforaspecificnumberoftimes.

Syntax
ThesyntaxofaforloopinTcllanguageis:
for{initialization}{condition}{increment}{
statement(s);
}

Hereistheflowofcontrolinaforloop:
Theinitializationstepisexecutedfirst,andonlyonce.Thisstepallowsyou
todeclareandinitializeanyloopcontrolvariables.Youarenotrequiredtoput
astatementhere,aslongasasemicolonappears.
Next, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of
controljumpstothenextstatementjustaftertheforloop.
Afterthebodyoftheforloopexecutes,theflowofcontroljumpsbackupto
the increment statement. This statement allows you to update any loop
control variables. This statement can be left blank, as long as a semicolon
appearsafterthecondition.
Theconditionisnowevaluatedagain.Ifitistrue,theloopexecutesandthe
process repeats itself (body of loop, then increment step, and then again
condition).Aftertheconditionbecomesfalse,theforloopterminates.

FlowDiagram
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

35/139

5/22/2016

TclTkQuickGuide

Example
#!/usr/bin/tclsh
#forloopexecution
for{seta10}{$a<20}{incra}{
puts"valueofa:$a"
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
valueofa:10
valueofa:11
valueofa:12
valueofa:13
valueofa:14
valueofa:15
valueofa:16
valueofa:17
valueofa:18
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

36/139

5/22/2016

TclTkQuickGuide

valueofa:19

TclNestedLoops
Tclallowstouseoneloopinsideanotherloop.Followingsectionshowsfewexamples
toillustratetheconcept.

Syntax
ThesyntaxforanestedforloopstatementinTcllanguageisasfollows:
for{initialization}{condition}{increment}{
for{initialization}{condition}{increment}{
statement(s);
}
statement(s);
}

ThesyntaxforanestedwhileloopstatementinTcllanguageisasfollows:
while{condition}{
while{condition}{
statement(s);
}
statement(s);
}

Afinalnoteonloopnestingisthatyoucanputanytypeofloopinsideofanyother
typeofloop.Forexample,aforloopcanbeinsideawhilelooporviceversa.

Example
The following program uses a nested for loop to find the prime numbers from 2 to
100:
#!/usr/bin/tclsh
setj0;
for{seti2}{$i<100}{incri}{
for{setj2}{$j<=[expr$i/$j]}{incrj}{
if{[expr$i%$j]==0}{
break
}
}
if{$j>[expr$i/$j]}{
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

37/139

5/22/2016

TclTkQuickGuide

puts"$iisprime"
}
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
2isprime
3isprime
5isprime
7isprime
11isprime
13isprime
17isprime
19isprime
23isprime
29isprime
31isprime
37isprime
41isprime
43isprime
47isprime
53isprime
59isprime
61isprime
67isprime
71isprime
73isprime
79isprime
83isprime
89isprime
97isprime

LoopControlStatements
Loopcontrolstatementschangeexecutionfromitsnormalsequence.Whenexecution
leavesascope,allautomaticobjectsthatwerecreatedinthatscopearedestroyed.
Tclsupportsthefollowingcontrolstatements.
ControlStatement

Description

breakstatement

Terminatesthelooporswitchstatementandtransfers
executiontothestatementimmediatelyfollowingtheloopor

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

38/139

5/22/2016

TclTkQuickGuide

switch.
continuestatement

Causesthelooptoskiptheremainderofitsbodyand
immediatelyretestitsconditionpriortoreiterating.

TclbreakStatement
ThebreakstatementinTcllanguageisusedforterminatingaloop.Whenthebreak
statement is encountered inside a loop, the loop is immediately terminated and
programcontrolresumesatthenextstatementfollowingtheloop.
Ifyouareusingnestedloops(i.e.,oneloopinsideanotherloop),thebreakstatement
willstoptheexecutionoftheinnermostloopandstartexecutingthenextlineofcode
aftertheblock.

Syntax
ThesyntaxforabreakstatementinTclisasfollows:
break;

FlowDiagram

Example

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

39/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
seta10
#whileloopexecution
while{$a<20}{
puts"valueofa:$a"
incra
if{$a>15}{
#terminatetheloopusingbreakstatement
break
}
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
valueofa:10
valueofa:11
valueofa:12
valueofa:13
valueofa:14
valueofa:15

TclcontinueStatement
ThecontinuestatementinTcllanguageworkssomewhatlikethebreakstatement.
Insteadofforcingtermination,however,continueforcesthenextiterationoftheloop
totakeplace,skippinganycodeinbetween.
For the for loop, continue statement causes the conditional test and increment
portionsofthelooptoexecute.Forthewhileloop,continuestatementpassesthe
programcontroltotheconditionaltests.

Syntax
ThesyntaxforacontinuestatementinTclisasfollows:
continue;

FlowDiagram

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

40/139

5/22/2016

TclTkQuickGuide

Example
#!/usr/bin/tclsh
seta10
#doloopexecution
while{$a<20}{
if{$a==15}{
#skiptheiteration

incra
continue
}
puts"valueofa:$a"
incra
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
valueofa:10
valueofa:11
valueofa:12
valueofa:13
valueofa:14
valueofa:16
valueofa:17
valueofa:18
valueofa:19

TheInfiniteLoop
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

41/139

5/22/2016

TclTkQuickGuide

A loop becomes infinite loop if a condition never becomes false. The while loop is
traditionally used for this purpose. You can make an endless loop by leaving the
conditionalexpressionas1.
while{1}{
puts"Thisloopwillrunforever."
}

Whentheconditionalexpressionisabsent,itisassumedtobetrue.Tclprogrammers
morecommonlyusethewhile{1}constructtosignifyaninfiniteloop.
NOTE:YoucanterminateaninfiniteloopbypressingCtrl+Ckeys.

TclArrays
Anarrayisasystematicarrangementofgroupofelementsusingindices.Thesyntax
fortheconventionalarrayisshownbelow.
setArrayName(Index)value

Anexampleforcreatingsimplearrayisshownbelow.
#!/usr/bin/tclsh
setlanguages(0)Tcl
setlanguages(1)"CLanguage"
puts$languages(0)
puts$languages(1)

Whenabovecodeisexecuted,itproducesfollowingresult.
Tcl
CLanguage

Sizeofarray
Thesyntaxforcalculatingsizearrayisshownbelow.
[arraysizevariablename]

Anexampleforprintingthesizeisshownbelow.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

42/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
setlanguages(0)Tcl
setlanguages(1)"CLanguage"
puts[arraysizelanguages]

Whenabovecodeisexecuted,itproducesfollowingresult.
2

ArrayIteration
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. A simple array iteration for printing elements of the
arrayisshownbelow.
#!/usr/bin/tclsh
setlanguages(0)Tcl
setlanguages(1)"CLanguage"
for{setindex0}{$index<[arraysizelanguages]}{incrindex}{
puts"languages($index):$languages($index)"
}

Whenabovecodeisexecuted,itproducesfollowingresult.
languages(0):Tcl
languages(1):CLanguage

AssociativeArrays
In Tcl, all arrays by nature are associative. Arrays are stored and retrieved without
anyspecificorder.Associativearrayshaveanindexthatisnotnecessarilyanumber,
and can be sparsely populated. A simple example for associative array with non
numberindicesisshownbelow.
#!/usr/bin/tclsh
setpersonA(Name)"Dave"
setpersonA(Age)14
puts$personA(Name)
puts$personA(Age)

Whenabovecodeisexecuted,itproducesfollowingresult.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

43/139

5/22/2016

TclTkQuickGuide

Dave
14

Indicesofarray
Thesyntaxforretrievingindicesofarrayisshownbelow.
[arraynamesvariablename]

Anexampleforprintingthesizeisshownbelow.
#!/usr/bin/tclsh
setpersonA(Name)"Dave"
setpersonA(Age)14
puts[arraynamespersonA]

Whenabovecodeisexecuted,itproducesfollowingresult.
AgeName

Iterationofassociativearray
Youcanusetheindicesofarraytoiteratethroughtheassociativearray.Anexample
isshownbelow.
#!/usr/bin/tclsh
setpersonA(Name)"Dave"
setpersonA(Age)14
foreachindex[arraynamespersonA]{
puts"personA($index):$personA($index)"
}

Whenabovecodeisexecuted,itproducesfollowingresult.
personA(Age):14
personA(Name):Dave

TclStrings
TheprimitivedatatypeofTclisstringandoftenwecanfindquotesonTclasstring
only language. These strings can contain alphanumeric character, just numbers,
boolean, or even binary data. Tcl uses 16 bit unicode characters and alphanumeric
characterscancontainlettersincludingnonLatincharacters,numberorpunctuation.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

44/139

5/22/2016

TclTkQuickGuide

Boolean value can be represented as 1, yes or true for true and 0, no, or false for
false.

StringRepresentations
Unlike other languages, in Tcl, you need not include double quotes when it's only a
singleword.Anexamplecanbe,
#!/usr/bin/tclsh
setmyVariablehello
puts$myVariable

Whenabovecodeisexecuted,itproducesfollowingresult.
hello

Whenwewanttorepresentmultiplestrings,wecanuseeitherdoublequotesorcurly
braces.Itisshownbelow.
#!/usr/bin/tclsh
setmyVariable"helloworld"
puts$myVariable
setmyVariable{helloworld}
puts$myVariable

Whenabovecodeisexecuted,itproducesfollowingresult.
helloworld
helloworld

Stringescapesequence
Acharacterliteralcanbeaplaincharacter(e.g.,'x'),anescapesequence(e.g.,'\t'),
orauniversalcharacter(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,youhavealistofsomeofsuchescapesequencecodes:
Escapesequence

Meaning

\\

\character

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

45/139

5/22/2016

TclTkQuickGuide

\'

'character

\"

"character

\?

?character

\a

Alertorbell

\b

Backspace

\f

Formfeed

\n

Newline

\r

Carriagereturn

\t

Horizontaltab

\v

Verticaltab

Followingistheexampletoshowfewescapesequencecharacters:
#!/usr/bin/tclsh
puts("Hello\tWorld\n\n");

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
HelloWorld

Stringcommand
Thelistofsubcommandsforstringcommandarelistedinthefollowingtable.
SN

MethodswithDescription

comparestring1string2
Comparesstring1andstring2lexographically.Returns0ifequal,1ifstring1
comesbeforestring2,else1.

string1string2
Returnstheindexfirstoccurrenceofstring1instring2.Ifnotfound,returns1.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

46/139

5/22/2016

TclTkQuickGuide

indexstringindex
Returnsthecharacteratindex.

laststring1string2
Returnstheindexlastoccurrenceofstring1instring2.Ifnotfound,returns1.

lengthstring
Returnsthelengthofstring.

matchpatternstring
Returns1ifthestringmatchesthepattern.

rangestringindex1index2
Returntherangeofcharactersinstringfromindex1toindex2.

tolowerstring
Returnsthelowercasestring.

toupperstring
Returnstheuppercasestring.

10

trimstring?trimcharacters?
Removes trimcharacters in both ends of string. The default trimcharacters is
whitespace.

11

trimleftstring?trimcharacters?
Removestrimcharactersinleftbeginningofstring.Thedefaulttrimcharacters
iswhitespace.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

47/139

5/22/2016

12

TclTkQuickGuide

trimrightstring?trimcharacters?
Removes trimcharacters in left end of string. The default trimcharacters is
whitespace.

13

wordendfindstringindex
Return the index in findstring of the character after the word containing the
characteratindex.

14

wordstartfindstringindex
Returntheindexinfindstringofthefirstcharacterinthewordcontainingthe
characteratindex.

ExamplesofsomethecommonlyusedTclstringsubcommandsaregivenbelow.

Stringcomparison
#!/usr/bin/tclsh
sets1"Hello"
sets2"World"
sets3"World"
puts[stringcompares1s2]
if{[stringcompares2s3]==0}{
puts"String\'s1\'and\'s2\'aresame.";
}
if{[stringcompares1s2]==1}{
puts"String\'s1\'comesbefore\'s2\'.";
}
if{[stringcompares2s1]==1}{
puts"String\'s2\'comesbefore\'s1\'.";
}

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
1
String's1'comesbefore's2'.
String's2'comesbefore's1'.

Indexofstring
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

48/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
sets1"HelloWorld"
sets2"o"
puts"Firstoccurrenceof$s2ins1"
puts[stringfirst$s2$s1]
puts"Characteratindex0ins1"
puts[stringindex$s10]
puts"Lastoccurrenceof$s2ins1"
puts[stringlast$s2$s1]
puts"Wordendindexins1"
puts[stringwordend$s120]
puts"Wordstartindexins1"
puts[stringwordstart$s120]

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Firstoccurrenceofoins1
4
Characteratindex0ins1
H
Lastoccurrenceofoins1
7
Wordendindexins1
11
Wordstartindexins1
6

Lengthofstring
#!/usr/bin/tclsh
sets1"HelloWorld"
puts"Lengthofstrings1"
puts[stringlength$s1]

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Lengthofstrings1
11

Handlingcases

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

49/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
sets1"HelloWorld"
puts"Uppercasestringofs1"
puts[stringtoupper$s1]
puts"Lowercasestringofs1"
puts[stringtolower$s1]

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Uppercasestringofs1
HELLOWORLD
Lowercasestringofs1
helloworld

Trimmingcharacters
#!/usr/bin/tclsh
sets1"HelloWorld"
sets2"World"
puts"Trimright$s2in$s1"
puts[stringtrimright$s1$s2]
sets2"Hello"
puts"Trimleft$s2in$s1"
puts[stringtrimleft$s1$s2]
sets1"HelloWorld"
sets2""
puts"Trimcharacterss1onbothsidesofs2"
puts[stringtrim$s1$s2]

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
TrimrightWorldinHelloWorld
Hello
TrimleftHelloinHelloWorld
World
Trimcharacterss1onbothsidesofs2
HelloWorld

Matchingstrings

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

50/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
sets1"test@test.com"
sets2"*@*.com"
puts"Matchingpatterns2ins1"
puts[stringmatch"*@*.com"$s1]
puts"Matchingpatterntclins1"
puts[stringmatch{tcl}$s1]

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
Matchingpatterns2ins1
1
Matchingpatterntclins1
0

Appendcommand
#!/usr/bin/tclsh
sets1"Hello"
appends1"World"
puts$s1

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
HelloWorld

Formatcommand
ThefollowingtableshowsthelistofformatspecifiersavailableinTcl.
Specifier

Use

%s

Stringrepresentation

%d

Integerrepresentation

%f

Floatingpointrepresentation

%e

Floatingpointrepresentationwithmantissaexponentform

%x

Hexadecimalrepresentation

Somesimpleexamplesaregivenbelow.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

51/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
puts[format"%f"43.5]
puts[format"%e"43.5]
puts[format"%d%s"4tuts]
puts[format"%s""TclLanguage"]
puts[format"%x"40]

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
43.500000
4.350000e+01
4tuts
TclLanguage
28

Scancommand
scan command is used for parsing a string based to the format specifier. Some
examplesareshownbelow.
#!/usr/bin/tclsh
puts[scan"90"{%[09]}m]
puts[scan"abc"{%[az]}m]
puts[scan"abc"{%[AZ]}m]
puts[scan"ABC"{%[AZ]}m]

Whentheabovecodeiscompiledandexecuted,itproducesthefollowingresult:
1
1
0
1

TclLists
ListisoneofthebasicdatatypeavailableinTcl.Itisusedforrepresentinganordered
collectionofitems.Itcanincludedifferenttypesofitemsinthesamelist.Further,a
listcancontainanotherlist.
An important thing that needs to be noted is that these lists are represented as
strings completely and processed to form individual items when required. So avoid
largelistsandinsuchcasesusearray.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

52/139

5/22/2016

TclTkQuickGuide

Creatingalist
Thegeneralsyntaxforlistisgivenbelow.
setlistName{item1item2item3..itemn}
#or
setlistName[listitem1item2item3]
#or
setlistName[split"itemsseparatedbyacharacter"split_character]

Someexamplesaregivenbelow.
#!/usr/bin/tclsh
setcolorList1{redgreenblue}
setcolorList2[listredgreenblue]
setcolorList3[split"red_green_blue"_]
puts$colorList1
puts$colorList2
puts$colorList3

Whenabovecodeisexecuted,itproducesfollowingresult.
redgreenblue
redgreenblue
redgreenblue

Appendingitemtoalist
Thesyntaxforappendingitemtoalistisgivenbelow.
appendlistNamesplit_charactervalue
#or
lappendlistNamevalue

Someexamplesaregivenbelow.
#!/usr/bin/tclsh
setvarorange
appendvar"""blue"
lappendvar"red"
lappendvar"green"
puts$var

Whenabovecodeisexecuted,itproducesfollowingresult.
orangeblueredgreen

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

53/139

5/22/2016

TclTkQuickGuide

Lengthoflist
Thesyntaxforlengthoflistisgivenbelow.
llengthlistName

Exampleforlengthoflistisgivenbelow.
#!/usr/bin/tclsh
setvar{orangeblueredgreen}
puts[llength$var]

Whenabovecodeisexecuted,itproducesfollowingresult.
4

Listitematindex
Thesyntaxforselectinglistitematspecificindexisgivenbelow.
lindexlistnameindex

Exampleforlistitematindexisgivenbelow.
#!/usr/bin/tclsh
setvar{orangeblueredgreen}
puts[lindex$var1]

Whenabovecodeisexecuted,itproducesfollowingresult.
blue

Insertitematindex
Thesyntaxforinsertinglistitemsatspecificindexisgivenbelow.
linsertlistnameindexvalue1value2..valuen

Exampleforinsertinglistitematspecificindexisgivenbelow.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

54/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
setvar{orangeblueredgreen}
setvar[linsert$var3blackwhite]
puts$var

Whenabovecodeisexecuted,itproducesfollowingresult.
orangeblueredblackwhitegreen

Replaceitemsatindices
Thesyntaxforreplacinglistitemsatspecificindicesisgivenbelow.
lreplacelistnamefirstindexlastindexvalue1value2..valuen

Exampleforreplacinglistitemsatspecificindicesisgivenbelow.
#!/usr/bin/tclsh
setvar{orangeblueredgreen}
setvar[lreplace$var23blackwhite]
puts$var

Whenabovecodeisexecuted,itproducesfollowingresult.
orangeblueblackwhite

Setitematindex
Thesyntaxforsettinglistitematspecificindexisgivenbelow.
lsetlistnameindexvalue

Exampleforsettinglistitematspecificindexisgivenbelow.
#!/usr/bin/tclsh
setvar{orangeblueredgreen}
lsetvar0black
puts$var

Whenabovecodeisexecuted,itproducesfollowingresult.
blackblueredgreen

Transformlisttovariables
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

55/139

5/22/2016

TclTkQuickGuide

Thesyntaxforcopyingvaluestovariablesisgivenbelow.
lassignlistnamevariable1variable2..variablen

Examplefortransforminglistintovariablesisgivenbelow.
#!/usr/bin/tclsh
setvar{orangeblueredgreen}
lassign$varcolour1colour2
puts$colour1
puts$colour2

Whenabovecodeisexecuted,itproducesfollowingresult.
orange
blue

Sortingalist
Thesyntaxforsortingalistisgivenbelow.
lsortlistname

Exampleforsortingalistisgivenbelow.
#!/usr/bin/tclsh
setvar{orangeblueredgreen}
setvar[lsort$var]
puts$var

Whenabovecodeisexecuted,itproducesfollowingresult.
bluegreenorangered

TclDictionary
A dictionary is an arrangement for mapping values to keys. The syntax for the
conventionaldictionaryisshownbelow.
dictsetdictnamekeyvalue
#or
dictcreatedictnamekey1value1key2value2..keynvaluen

Someexamplesforcreatingdictionaryisshownbelow.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

56/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
dictsetcolourscolour1red
puts$colours
dictsetcolourscolour2green
puts$colours
setcolours[dictcreatecolour1"black"colour2"white"]
puts$colours

Whenabovecodeisexecuted,itproducesfollowingresult.
colour1red
colour1redcolour2green
colour1blackcolour2white

Sizeofdict
Thesyntaxforgettingsizeofdictisshownbelow.
[dictsizedictname]

Anexampleforprintingthesizeisshownbelow.
#!/usr/bin/tclsh
setcolours[dictcreatecolour1"black"colour2"white"]
puts[dictsize$colours]

Whenabovecodeisexecuted,itproducesfollowingresult.
2

DictionaryIteration
A simple dictionary iteration for printing keys and valued of the dictionary is shown
below.
#!/usr/bin/tclsh
setcolours[dictcreatecolour1"black"colour2"white"]
foreachitem[dictkeys$colours]{
setvalue[dictget$colours$item]
puts$value
}

Whenabovecodeisexecuted,itproducesfollowingresult.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

57/139

5/22/2016

TclTkQuickGuide

black
white

Valueforkeyindict
Thesyntaxforretrievingvalueforkeyindictisshownbelow.
[dictget$dictname$keyname]

Anexampleforretrievingvalueforkeyisgivenbelow.
#!/usr/bin/tclsh
setcolours[dictcreatecolour1"black"colour2"white"]
setvalue[dictget$colourscolour1]
puts$value

Whenabovecodeisexecuted,itproducesfollowingresult.
black

Allkeysindict
Thesyntaxforretrievingallkeysindictisshownbelow.
[dictkeys$dictname]

Anexampleforprintingallkeysisshownbelow.
#!/usr/bin/tclsh
setcolours[dictcreatecolour1"black"colour2"white"]
setkeys[dictkeys$colours]
puts$keys

Whenabovecodeisexecuted,itproducesfollowingresult.
colour1colour2

Allvaluesindict
Thesyntaxforretrievingallvaluesindictisshownbelow.
[dictvalues$dictname]

Anexampleforprintingallvaluesisshownbelow.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

58/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
setcolours[dictcreatecolour1"black"colour2"white"]
setvalues[dictvalues$colours]
puts$values

Whenabovecodeisexecuted,itproducesfollowingresult.
blackwhite

Keyexistsindict
Thesyntaxforcheckingifakeyexistsindictisshownbelow.
[dictvalues$dictname]

Anexampleforcheckingifakeyexistsindictisshownbelow.
#!/usr/bin/tclsh
setcolours[dictcreatecolour1"black"colour2"white"]
setresult[dictexists$colourscolour1]
puts$result

Whenabovecodeisexecuted,itproducesfollowingresult.
1

TclProcedures
Procedures are nothing but code blocks with series of commands that provides a
specific reusable functionality. It is used to avoid same code being repeated in
multiple locations. Procedures are equivalent to the functions used in many
programming languages and are made available in Tcl with the help of proc
command.
Thesyntaxofcreatingasimpleprocedureisshownbelow.
procprocedureName{arguments}{
body
}

Asimpleexampleforprocedureisgivenbelow.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

59/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
prochelloWorld{}{
puts"Hello,World!"
}
helloWorld

Whenabovecodeisexecuted,itproducesfollowingresult.
Hello,World!

Procedureswithmultiplearguments
Anexampleforprocedurewithargumentsisshownbelow.
#!/usr/bin/tclsh
procadd{ab}{
return[expr$a+$b]
}
puts[add1030]

Whenabovecodeisexecuted,itproducesfollowingresult.
40

Procedureswithvariablearguments
Anexampleforprocedurewithargumentsisshownbelow.
#!/usr/bin/tclsh
procavg{numbers}{
setsum0
foreachnumber$numbers{
setsum[expr$sum+$number]

}
setaverage[expr$sum/[llength$numbers]]
return$average
}
puts[avg{70805060}]
puts[avg{708050}]

Whenabovecodeisexecuted,itproducesfollowingresult.
65
66

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

60/139

5/22/2016

TclTkQuickGuide

Procedureswithdefaultarguments
Defaultargumentsareusedtoprovidedefaultvaluesthatcanbeusedifnovalueis
provided. An example for procedure with default arguments which is sometimes
referredasimplicitargumentsisshownbelow.
#!/usr/bin/tclsh
procadd{a{b100}}{
return[expr$a+$b]
}
puts[add1030]
puts[add10]

Whenabovecodeisexecuted,itproducesfollowingresult.
40
110

Recursiveprocedures
Anexampleforrecursiveproceduresisshownbelow.
#!/usr/bin/tclsh
procfactorial{number}{
if{$number<=1}{
return1
}
return[expr$number*[factorial[expr$number1]]]
}
puts[factorial3]
puts[factorial5]

Whenabovecodeisexecuted,itproducesfollowingresult.
6
120

TclPackages
Packages are used for creating reusable units of code. A package consists of a
collectionoffilesthatprovidespecificfunctionality.Thiscollectionoffilesisidentified
byapackagenameandcanhavemultipleversionsofsamefiles.Thepackagecanbe
acollectionofTclscripts,binarylibraryoracombinationofboth.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

61/139

5/22/2016

TclTkQuickGuide

Package uses the concept of namespace to avoid collision of variable names and
procedurenames.Checkoutmoreinournextnamespace

tutorial.

Creatingpackage
Package can be created with the help of minimum two files. One file contains the
packagecode.Otherfilecontainstheindexpackagefilefordeclaringyourpackage.
Thelistofstepsforcreatingandusingpackageisgivenbelow.

STEP1:CREATINGCODE
Create code for package inside a folder say HelloWorld. Let the file be named
HelloWorld.tclwithcodeasshownbelow.
#/Users/rajkumar/Desktop/helloworld/HelloWorld.tcl
#Createthenamespace
namespaceeval::HelloWorld{

#ExportMyProcedure
namespaceexportMyProcedure

#MyVariables
setversion1.0
setMyDescription"HelloWorld"

#Variableforthepathofthescript
variablehome[filejoin[pwd][filedirname[infoscript]]]

#DefinitionoftheprocedureMyProcedure
proc::HelloWorld::MyProcedure{}{

puts$HelloWorld::MyDescription
}
packageprovideHelloWorld$HelloWorld::version
packagerequireTcl8.0

STEP2:CREATINGPACKAGEINDEX
Open tclsh. Switch to HelloWorld directory and use the pkg_mkIndex command to
createtheindexfileasshownbelow.
%cd/Users/rajkumar/Desktop/helloworld
%pkg_mkIndex.*.tcl

STEP3:ADDINGDIRECTORYTOAUTOPATH
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

62/139

5/22/2016

TclTkQuickGuide

Usethelappendcommandtoaddthepackagetothegloballistasshownbelow.
%lappendauto_path"/Users/rajkumar/Desktop/helloworld"

STEP4:ADDINGPACKAGE
Nextaddpackagetoprogramusingpackagerequirestatementasshownbelow.
%packagerequireHelloWorld1.0

STEP5:INVOKINGPROCEDURE
Now,everythingbeingsetup,wecaninvokeourprocedureasshownbelow.
%puts[HelloWorld::MyProcedure]

Youwillgetthefollowingresult.
HelloWorld

Firsttwostepscreatethepackage.Oncepackageiscreated,youcanuseitinanyTcl
filebyaddingthelastthreestatementsasshownbelow.
lappendauto_path"/Users/rajkumar/Desktop/helloworld"
packagerequireHelloWorld1.0
puts[HelloWorld::MyProcedure]

Youwillgetthefollowingresult.
HelloWorld

TclNamespaces
Namespace is a container for set of identifiers that is used to group variables and
procedures.NamespacesareavailablefromTclversion8.0.Beforetheintroductionof
namespaces, there was single global scope. Now with namespaces, we have
additionalpartitionsofglobalscope.

Creatingnamespace
Namespaces are created using the namespace command. A simple example for
creatingnamespaceisshownbelow

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

63/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
namespaceevalMyMath{
#Createavariableinsidethenamespace
variablemyResult
}
#Createproceduresinsidethenamespace
procMyMath::Add{ab}{
set::MyMath::myResult[expr$a+$b]
}
MyMath::Add1023
puts$::MyMath::myResult

Whenabovecodeisexecuted,itproducesfollowingresult.
33

Intheaboveprogram,youcanseethereisanamespacewithavariablemyResult
andaprocedureAdd.Thismakesitpossibletocreatevariablesandprocedureswith
samenamesunderdifferentnamespaces.

Nestednamespaces
Tclallowsnestingofnamespaces.Asimpleexamplefornestingnamespacesisgiven
below.
#!/usr/bin/tclsh
namespaceevalMyMath{
#Createavariableinsidethenamespace
variablemyResult
}
namespaceevalextendedMath{
#Createavariableinsidethenamespace
namespaceevalMyMath{
#Createavariableinsidethenamespace
variablemyResult
}
}
set::MyMath::myResult"test1"
puts$::MyMath::myResult
set::extendedMath::MyMath::myResult"test2"
puts$::extendedMath::MyMath::myResult

Whentheabovecodeisexecuted,itproducesthefollowingresult.
test1
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

64/139

5/22/2016

TclTkQuickGuide

test2

Importingandexportingnamespace
You can see in the previous namespace examples, we use lot of scope resolution
operatorandit'smorecomplextouse.Wecanavoidthisbyimportingandexporting
namespaces.Anexampleisgivenbelow.
#!/usr/bin/tclsh
namespaceevalMyMath{
#Createavariableinsidethenamespace
variablemyResult
namespaceexportAdd
}
#Createproceduresinsidethenamespace
procMyMath::Add{ab}{
return[expr$a+$b]
}
namespaceimportMyMath::*
puts[Add1030]

Whenabovecodeisexecuted,itproducesfollowingresult.
40

Forgetnamespace
You can remove an imported namespace by using forget subcommand. A simple
exampleisshownbelow.
#!/usr/bin/tclsh
namespaceevalMyMath{
#Createavariableinsidethenamespace
variablemyResult
namespaceexportAdd
}
#Createproceduresinsidethenamespace
procMyMath::Add{ab}{
return[expr$a+$b]
}
namespaceimportMyMath::*
puts[Add1030]
namespaceforgetMyMath::*

Whenabovecodeisexecuted,itproducesfollowingresult.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

65/139

5/22/2016

TclTkQuickGuide

40

TclFileI/O
Tclsupportsfilehandlingwiththehelpofthebuiltincommandsopen,read,puts,gets
andclose.
Afilerepresentsasequenceofbytes,doesnotmatterifitisatextfileorbinaryfile.

OpeningFiles
Tcl uses the open command to open files in Tcl. The syntax for opening a file is as
follows.
openfileNameaccessMode

Here,filenameisstringliteral,whichyouwillusetonameyourfileandaccessMode
canhaveoneofthefollowingvalues:
Mode

Description

Opensanexistingtextfileforreadingpurposeandthefilemustexist.Thisis
thedefaultmodeusedwhennoaccessModeisspecified.

Opensatextfileforwriting,ifitdoesnotexistthenanewfileiscreatedelse
existingfileistruncated.

Opensatextfileforwritinginappendingmodeandfilemustexist.Hereyour
programwillstartappendingcontentintheexistingfilecontent.

r+

Opensatextfileforreadingandwritingboth.Filemustexistalready.

w+

Opensatextfileforreadingandwritingboth.Itfirsttruncatethefiletozero
lengthifitexistsotherwisecreatethefileifitdoesnotexist.

a+

Opensatextfileforreadingandwritingboth.Itcreatesthefileifitdoesnot
exist.Thereadingwillstartfromthebeginningbutwritingcanonlybe
appended.

ClosingaFile
Tocloseafile,usetheclosecommand.Thesyntaxforcloseisasfollows.
closefileName
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

66/139

5/22/2016

TclTkQuickGuide

Any file that has been opened by a program must be closed when the program
finishesusingthatfile.Inmostcasesthefilesneednotbeclosedexplicitlytheyare
closedautomaticallywhenFileobjectsareterminatedautomatically.

WritingaFile
putscommandisusedtowritetoanopenfile.
puts$filename"texttowrite"

Asimpleexampleforwritingtoafileisshownbelow.
#!/usr/bin/tclsh
setfp[open"input.txt"w+]
puts$fp"test"
close$fp

Whentheabovecodeiscompiledandexecuted,itcreatesanewfileinput.txtinthe
directorythatithasbeenstartedunder(intheprogram'sworkingdirectory).

ReadingaFile
Followingisthesimplecommandtoreadfromafile:
setfile_data[read$fp]

Acompleteexampleofreadandwriteisshownbelow.
#!/usr/bin/tclsh
setfp[open"input.txt"w+]
puts$fp"test"
close$fp
setfp[open"input.txt"r]
setfile_data[read$fp]
puts$file_data
close$fp

Whentheabovecodeiscompiledandexecuted,itreadsthefilecreatedinprevious
sectionandproducesthefollowingresult:
test

Hereisanotherexampleforreadingfiletillendoffilelinebyline.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

67/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
setfp[open"input.txt"w+]
puts$fp"test\ntest"
close$fp
setfp[open"input.txt"r]
while{[gets$fpdata]>=0}{
puts$data
}
close$fp

Whentheabovecodeiscompiledandexecuted,itreadsthefilecreatedinprevious
sectionandproducesthefollowingresult:
test
test

TclErrorHandling
Error handling in Tcl is provided with the help of error and catch commands. The
syntaxforeachofthesecommandsisshownbelow.

Errorsyntax
errormessageinfocode

Intheaboveerrorcommandsyntax,messageistheerrormessage,infoissetinthe
globalvariableerrorInfoandcodeissetintheglobalvariableerrorCode.

Catchsyntax
catchscriptresultVarName

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
returns0ifthereisnoerrorand1ifthereisanerror.
Anexampleforsimpleerrorhandlingisshownbelow.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

68/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
procDiv{ab}{
if{$b==0}{
error"Errorgeneratedbyerror""InfoStringforerror"401
}else{
return[expr$a/$b]
}
}
if{[catch{puts"Result=[Div100]"}errmsg]}{
puts"ErrorMsg:$errmsg"
puts"ErrorCode:$errorCode"
puts"ErrorInfo:\n$errorInfo\n"
}
if{[catch{puts"Result=[Div102]"}errmsg]}{
puts"ErrorMsg:$errmsg"
puts"ErrorCode:$errorCode"
puts"ErrorInfo:\n$errorInfo\n"
}

Whenabovecodeisexecuted,itproducesfollowingresult.
ErrorMsg:Errorgeneratedbyerror
ErrorCode:401
ErrorInfo:
InfoStringforerror
(procedure"Div"line1)
invokedfromwithin
"Div100"
Result=5

Asyoucanseeintheaboveexample,wecancreateourowncustomerrormessages.
Similarly, it is possible to catch the error generated by Tcl. An example is shown
below.
#!/usr/bin/tclsh
catch{setfile[openmyNonexistingfile.txt]}result
puts"ErrorMsg:$result"
puts"ErrorCode:$errorCode"
puts"ErrorInfo:\n$errorInfo\n"

Whenabovecodeisexecuted,itproducesfollowingresult.
ErrorMsg:couldn'topen"myNonexistingfile.txt":nosuchfileordirectory
ErrorCode:POSIXENOENT{nosuchfileordirectory}
ErrorInfo:
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

69/139

5/22/2016

TclTkQuickGuide

couldn'topen"myNonexistingfile.txt":nosuchfileordirectory
whileexecuting
"openmyNonexistingfile.txt"

TclBuiltinFunctions
Tcl provides a number of builtin functions (procedures) for various operations. This
includes,
Functionsforlist

handling.

Functionsforstring

handling.

Functionsforarray

handling.

Functionsfordictionary
FunctionsforFileI/O

handling.
handling.

Functionsforcreatingnamespaces

andpackages.

FunctionsforMathoperations.
FunctionsforSystemoperations.
Each of the above except for math and system functions are covered in earlier
chapters.Mathandsystembuiltinfunctionsareexplainedbelow.

MathFunctions
ThemathfunctionsavailableinTclarelistedinthefollowingtable.
SN

MethodName

Description

absarg

Calculatestheabsolutevalueofarg.

acosarg

Calculatesthearccosineofarg.

asinarg

Calculatesthearcsineofarg.

atanarg

Calculatesthearctangentofarg.

atan2yx

Calculatesthearctangentofthequotientofitsarguments(y/x).

ceilarg

Calculatesthesmallestintegergreaterthanorequaltoa

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

70/139

5/22/2016

TclTkQuickGuide

number.
7

cosarg

Calculatesthecosineofarg.

cosharg

Calculatesthehyperboliccosineofarg.

doublearg

Calculatesifargisafloatingpointvalue,returnsarg,otherwise
convertsargtofloatingpointandreturnstheconvertedvalue.

10

exparg

Calculatesanexponentialfunction(eraisedtothepowerof
arg).

11

floorarg

Calculatesthelargestintegerlessthanorequaltoarg.

12

fmodxy

Calculatesthefloatingpointremainderofthedivisionofxbyy.
Ifyis0,anerrorisreturned.

13

hypotxy

Calculatesthelengthofthehypotenuseofarightangled
trianglesqrt(x*x+y*y).

14

intarg

Calculatesifargisanintegervalueofthesamewidthasthe
machineword,returnsarg,otherwiseconvertsargtoan
integer.

15

logarg

Calculatesthenaturallogarithmofarg.

16

log10arg

Calculatesthebase10logarithmofarg.

17

powxy

Calculatesthevalueofxraisedtothepowery.Ifxisnegative,
ymustbeanintegervalue.

18

rand

Calculatesapseudorandomnumberbetween0and1.

19

roundarg

Calculatesthevalueofargroundedtothenearestinteger.

20

sinarg

Calculatesthesineofarg.

21

sinharg

Calculatesthehyperbolicsineofarg.

22

sqrtarg

Calculatesthesquarerootofarg.argmustbepositive.

23

srandarg

Calculatesapseudorandomnumberbetween0and1.Thearg,
whichmustbeaninteger,isusedtoresettheseedforthe
randomnumbergeneratorofrand.

24

tanarg

Calculatesthetangentofarg.

25

tanharg

Calculatesthehyperbolictangentofarg.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

71/139

5/22/2016

26

TclTkQuickGuide

widearg

Calculatesintegervalueatleast64bitswide(bysign
extensionifargisa32bitnumber)forargifitisnotone
already.

Someexamplesusingmathfunctionsaregivenbelow.
#!/usr/bin/tclsh
namespaceimport::tcl::mathfunc::*
puts[tan10]
puts[pow102]
puts[ceil10.34]
puts[hypot1020]
puts[srand45]
puts[log10]
puts[srand45]

Whentheabovecodeisexecuted,itproducesthefollowingresult.
0.6483608274590866
100.0
11.0
22.360679774997898
0.0003521866166741525
2.302585092994046
0.0003521866166741525

SystemFunctions
TheimportantsystemfunctionsinTclincludes,
clocksecondsfunctionwhichreturnscurrenttimeinseconds.
clockformatfunctionwhichformatsthesecondsintodateandtime.
clockscanfunctionwhichscanstheinputstringandconvertittoseconds.
openfunctionwhichisusedtoopenafile.
execfunctionwhichisusedtoexecuteasystemcommand.
closefunctionwhichisusedtocloseafile.
Someexamplesfortheabovefunctionsarelistedbelow.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

72/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/tclsh
#getseconds
setcurrentTime[clockseconds]
puts$currentTime
#getformat
puts"Thetimeis:[clockformat$currentTimeformat%H:%M:%S]"
puts"Thedateis:[clockformat$currentTimeformat%D]"
setdate"Jun15,2014"
puts[clockscan$dateformat{%b%d,%Y}]
puts[execls]
puts[execdir]
seta[openinput.txt]
puts[read$a];
puts$a
close$a

Whenabovecodeisexecuted,itproducesfollowingresult.
1402819756
Thetimeis:03:09:16
Thedateis:06/15/2014
1402808400
input.txt
main.tcl
input.txtmain.tcl

Thisisthefileyoucanusetoprovideinputtoyourprogramandlateronopenitinsideyourprogramtop
file3

Thefollowingtableprovidestheliststringsthatcanbeusedtoformatthedateand
time.
SN

Format

Description

%a

Dayinshortform,eg:Sun.

%A

Dayinfullformeg:Sunday.

%b

Monthinshortform.

%B

Monthinfullform.

%d

Dayofmonth

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

73/139

5/22/2016

TclTkQuickGuide

%j

Juliandayofyear.

%m

Monthinnumber.

%y

Yearintwodigits.

%Y

Yearinfourdigits.

10

%H

Hourin24hourclock.

11

%I

Hourin12hourclock.

12

%M

Minutes.

13

%S

Seconds.

14

%p

AMorPM.

15

%D

Dateinnumber,mm/dd/yy.

16

%r

Timein12hourclock.

17

%R

Timein24hourclockwithoutseconds.

18

%T

Timein24hourclockwithseconds.

19

%Z

TimeZoneNamelikeGMT,IST,ESTandsoon.

TclRegularExpressions
The "regexp" command is used to match a regular expression in Tcl. A regular
expressionisasequenceofcharactersthatcontainsasearchpattern.Itconsistsof
multiplerulesandthefollowingtableexplainstheserulesandcorrespondinguse.
SN

Rule

Description

Exactmatch.

[az]

Anylowercaseletterfromaz.

Anycharacter.

Beginningstringshouldmatch.

Endingstringshouldmatch

\^

Backlashsequencetomatchspecialcharacter^.Similarlyyou

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

74/139

5/22/2016

TclTkQuickGuide

canuseforothercharacters.
7

()

Addtheabovesequencesinsideparenthesistomakearegular
expression.

x*

Shouldmatch0ormoreoccurrencesoftheprecedingx.

x+

Shouldmatch1ormoreoccurrencesoftheprecedingx.

10

[az]?

Shouldmatch0or1occurrenceoftheprecedingx.

11

{digit}

Matchesexactlydigitoccurrencesofpreviousregexexpression.
Digitthatcontain09.

12

{digit,}

Matches3ormoredigitoccurrencesofpreviousregex
expression.Digitthatcontain09.

13

{digit1,digit2}

Occurrencesmatchestherangebetweendigit1anddigit2
occurrencesofpreviousregexexpression.

Syntax
Thesyntaxforregexisgivenbelow.
regexpoptionalSwitchespatternssearchStringfullMatchsubMatch1...subMatchn

Here,regexisthecommand.Wewillseeaboutoptionalswitcheslater.Patternsare
therulesasmentionedearlier.Searchstringistheactualstringonwhichtheregexis
performed. Full match is any variable to hold the result of matched regex result.
Submatch1toSubMatchnareoptionalsubMatchvariablethatholdstheresultofsub
matchpatterns.
Let's look at some simple examples before diving into complex ones. A simple
exampleforastringwithanyalphabets.Whenanyothercharacterisencounteredthe
regexsearchwillbestoppedandreturned.
#!/usr/bin/tclsh
regexp{([AZ,az]*)}"TclTutorial"ab
puts"FullMatch:$a"
puts"SubMatch1:$b"

Whenabovecodeisexecuted,itproducesfollowingresult.
FullMatch:Tcl
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

75/139

5/22/2016

TclTkQuickGuide

SubMatch1:Tcl

Multiplepatterns
The following example shows how to search for multiple patterns. This is example
patternforanyalphabetsfollowedbyanycharacterfollowedbyanyalphabets.
#!/usr/bin/tclsh
regexp{([AZ,az]*).([AZ,az]*)}"TclTutorial"abc
puts"FullMatch:$a"
puts"SubMatch1:$b"
puts"SubMatch2:$c"

Whenabovecodeisexecuted,itproducesfollowingresult.
FullMatch:TclTutorial
SubMatch1:Tcl
SubMatch2:Tutorial

Amodifiedversionoftheabovecodetoshowthatasubpatterncancontainmultiple
patternsisshownbelow.
#!/usr/bin/tclsh
regexp{([AZ,az]*.([AZ,az]*))}"TclTutorial"abc
puts"FullMatch:$a"
puts"SubMatch1:$b"
puts"SubMatch2:$c"

Whenabovecodeisexecuted,itproducesfollowingresult.
FullMatch:TclTutorial
SubMatch1:TclTutorial
SubMatch2:Tutorial

SwitchesforRegexcommand
ThelistofswitchesavailableinTclare,
nocase:Usedtoignorecase.
indices : Stores location of matched sub patterns instead of matched
characters.
line:Newlinesensitivematching.Ignoresthecharactersafternewline.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

76/139

5/22/2016

TclTkQuickGuide

startindex:Settheoffsetofstartofsearchpattern
:Markstheendofswitches
Intheaboveexamples,Ihavedeliberatelyused[AZ,az]forallalphabets,youcan
easilyusenocaseinsteadasshownbelow.
#!/usr/bin/tclsh
regexpnocase{([AZ]*.([AZ]*))}"TclTutorial"abc
puts"FullMatch:$a"
puts"SubMatch1:$b"
puts"SubMatch2:$c"

Whenabovecodeisexecuted,itproducesfollowingresult.
FullMatch:TclTutorial
SubMatch1:TclTutorial
SubMatch2:Tutorial

Anotherexampleusingswitchesisshownbelow.
#!/usr/bin/tclsh
regexpnocaseline{([AZ]*.([AZ]*))}"Tcl\nTutorial"ab
puts"FullMatch:$a"
puts"SubMatch1:$b"
regexpnocasestart4line{([AZ]*.([AZ]*))}"Tcl\nTutorial"ab
puts"FullMatch:$a"
puts"SubMatch1:$b"

Whenabovecodeisexecuted,itproducesfollowingresult.
FullMatch:Tcl
SubMatch1:Tcl
FullMatch:Tutorial
SubMatch1:Tutorial

TkOverview
Tk refers to Toolkit and it provides cross platform GUI widgets which helps you in
buildingaGraphicalUserInterface.ItwasdevelopedasanextensiontoTclscripting
language by John Ousterhout. Tk remained in development independently from Tcl
withversionbeingdifferenttoeachother,before,itwasmadeinsyncwithTclinv8.0.

FeaturesofTk
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

77/139

5/22/2016

TclTkQuickGuide

It is cross platform with support for Linux, Mac OS, Unix, and Microsoft Windows
operatingsystems.
Itisanopensource.
Itprovideshighlevelofextendibility.
Itiscustomizable.
Itisconfigurable.
Itprovidesalargenumberofwidgets.
ItcanbeusedwithmultipleotherdynamiclanguagesandnotjustTcl
GUIlooksidenticalacrossplatforms.

ApplicationsbuiltinTk
LargesuccessfulapplicationshavebeenbuiltinTcl/Tk.
DashboardSoftUserInterface
FormsGUIforRelationalDB
AdHocGUIforRelationalDB
Software/HardwareSystemDesign
XtaskTaskManagement
MusicologywithTclandTk
Calenderapp
Tkmail
TkDebugger

TkEnvironment
GenerallyallMacandLinuxmaccomewithTkpreinstalled.Incaseit'snotavailable
oryouneedthelatestversion,thenyoumayneedtoinstallit.Windowsdon'tcome
withTcl/Tkandyoumayneedtouseitsspecificbinarytoinstallit.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

78/139

5/22/2016

TclTkQuickGuide

TheTkInterpreter
It is just a small program that enables you to type Tk commands and have them
executed line by line. It stops execution of a tcl file in case it encounters an error
unlikeacompilerthatexecutesfully.
Let'shaveahelloWorld.tclfileasfollows.Wewillusethisasfirstprogramwerunon
platformyouchoose.
#!/usr/bin/wish
grid[ttk::button.mybuttontext"HelloWorld"]

The following section explains only how to install Tcl/Tk on each of the available
platforms.

InstallationonWindows
Download the latest version for windows installer

from the list of Active Tcl/Tk

binariesavailable.ActiveTcl/Tkcommunityeditionisfreeforpersonaluse.
Run the downloaded executable to install the Tcl and Tk which can be done by
followingtheonscreeninstructions.
NowwecanbuildandrunaTclfilesayhelloWorld.tclbyswitchingtofoldercontaining
thefileusingcdandthenusingthefollowingstep
C:\Tcl>wishhelloWorld.tcl

Pressenterandwewillseeanoutputasshownbelow.

InstallationonLinux
Most Linux operating systems comes with Tk inbuilt and you can get started right
awayinthosesystems.Incase,it'snotavailable,youcanusethefollowingcommand
todownloadandinstallTclTk.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

79/139

5/22/2016

TclTkQuickGuide

$yuminstalltcltk

NowwecanbuildandrunaTclfilesayhelloWorld.tclbyswitchingtofoldercontaining
thefileusingcdcommandandthenusingthefollowingstep
$wishhelloWorld.tcl

Pressenterandwewillseeanoutputsimilartothefollowing.

InstallationonDebianbasedsystems
Incase,it'snotavailableprebuiltinyourOS,youcanusethefollowingcommandto
downloadandinstallTclTk.
$sudoaptgetinstalltcltk

NowwecanbuildandrunaTclfilesayhelloWorld.tclbyswitchingtofoldercontaining
thefileusingcdcommandandthenusingthefollowingsteps
$wishhelloWorld.tcl

Pressenterandwewillseeanoutputsimilartothefollowing.

InstallationonMacOSX
Download the latest version for Mac OS X package

from the list of Active Tcl/Tk

binariesavailable.ActiveTclcommunityeditionisfreeforpersonaluse.
RunthedownloadedexecutabletoinstalltheActiveTclwhichcanbedonebyfollowing
theonscreeninstructions.
NowwecanbuildandrunaTclfilesayhelloWorld.tclbyswitchingtofoldercontaining
thefileusingcdcommandandthenusingthefollowingstep

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

80/139

5/22/2016

TclTkQuickGuide

$wishhelloWorld.tcl

Pressenterandwewillseeanoutputasshownbelow.

Installationfromsourcefiles
You can use the option of installing from source files when a binary package is not
available.ItisgenerallypreferredtouseTkbinariesforWindowsandMacOSX,so
onlycompilationofsourcesonunixbasedsystemisshownbelow.
Downloadthesourcefiles.
Nowusethefollowingcommandstoextract,compileandbuildafterswitching
tothedownloadedfolder.
$tarzxftk8.6.1src.tar.gz
$cdtcl8.6.1
$cdunix
$./configurewithtcl=../../tcl8.6.1/unixprefix=/optenablegcc
$make
$sudomakeinstall

Note : Make sure, you change the file name to the version you downloaded on
commands1and2intheabove.

TkSpecialVariables
In Tk, we classify some of the variables as special variables and they have a
predefinedusage/functionality.Thelistofspecialvariablesislistedbelow.
SpecialVariable

Description

tk_library

UsedforsettingthelocationofstandardTklibraries.

tk_patchLevel

ReferstothecurrentpatchleveloftheTkinterpreter.

tk_strictMotif

Whennonzero,TktriestoadheretoMotiflookandfeelasclosely
aspossible.

tk_version

DisplaystheTkversion.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

81/139

5/22/2016

TclTkQuickGuide

TheabovespecialvariableshavetheirspecialmeaningsfortheTkinterpreter.

ExamplesforusingTkspecialvariables
Letsseetheexamplesforspecialvariables.

TKVERSION
#!/usr/bin/wish
puts$tk_version

Whenyouruntheprogram,youwillgetasimilaroutputasshownbelow.
8.5

TKLIBRARYPATH
#!/usr/bin/wish
puts$tk_library

Whenyouruntheprogram,youwillgetasimilaroutputasshownbelow.
/Library/Frameworks/Tk.framework/Versions/8.6/Resources/Scripts

TKPATCHLEVEL
#!/usr/bin/wish
puts$tk_patchLevel

Whenyouruntheprogram,youwillgetasimilaroutputasshownbelow.
8.6.1

TKSTRICTMOTIF
#!/usr/bin/wish
puts$tk_strictMotif

Whenyouruntheprogram,youwillgetasimilaroutputasshownbelow.
0

TkWidgetsOverview
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

82/139

5/22/2016

TclTkQuickGuide

ThebasiccomponentofaTkbasedapplicationiscalledawidget.Acomponentisalso
sometimes called a window, since, in Tk, "window" and "widget" are often used
interchangeably.Tkisapackagethatprovidesarichsetofgraphicalcomponentsfor
creatinggraphicalapplicationswithTcl.
Tk provides a range of widgets ranging from basic GUI widgets like buttons and
menustodatadisplaywidgets.Thewidgetsareveryconfigurableastheyhavedefault
configurationsmakingthemeasytouse.
Tkapplicationsfollowawidgethierarchywhereanynumberofwidgetsmaybeplaced
withinanotherwidget,andthosewidgetswithinanotherwidget.Themainwidgetina
Tk program is referred to as the root widget and can be created by making a new
instanceoftheTkRootclass.

Creatingawidget
Thesyntaxforcreatingawidgetisgivenbelow.
typevariableNameargumentsoptions

Thetypeherereferstothewidgettypelikebutton,labelandsoon.Argumentscanbe
optional and required based on individual syntax of each widget. The options range
fromsizetoformattingofeachcomponent.

WidgetNamingconvention
Widgetusesastructuresimilartonamingpackages.InTk,therootwindowisnamed
withaperiod(.)andanelementinwindow,forexamplebuttonisnamed.myButton1.
The variable name should start with a lowercase letter, digit, or punctuation mark
(except a period). After the first character, other characters may be uppercase or
lowercase letters, numbers, or punctuation marks (except periods). It is
recommendedtousealowercaselettertostartthelabel.

ColorNamingconvention
The colors can be declared using name like red, green and so on. It can also use
hexadecimalrepresentingwith#.Thenumberofhexadecimaldigitscanbe3,6,9or
12.

Dimensionconvention
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

83/139

5/22/2016

TclTkQuickGuide

The default unit is pixels and it is used when we specify no dimension. The other
dimensionsareiforinches,mformillimeters,cforcentimetersandpforpoints.

CommonOptions
Therearesomanycommonoptionsavailabletoallwidgetsandtheyarelistedbelow
intable.
SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

borderwidthwidth

Usedtodrawwithborderin3Deffects.

fontfontDescriptor

Usedtosetfontforwidget.

foregroundcolor

Usedtosetforegroundcolorforwidget.

heightnumber

Usedtosetheightforwidget.

highlightbackgroundcolor

Usedtosetthecolorrectangletodrawarounda
widgetwhenthewidgetdoesnothaveinput
focus.

highlightcolorcolor

Usedtosetthecolorrectangletodrawarounda
widgetwhenthewidgethasinputfocus.

padxnumber

Setsthepadxforthewidget.

padynumber

Setsthepadyforthewidget.

10

reliefcondition

Setsthe3Dreliefforthiswidget.Thecondition
mayberaised,sunken,flat,ridge,solid,or
groove.

11

texttext

Setsthetextforthewidget.

12

textvariablevarName

Variableassociatedwiththewidget.Whenthe
textofwidgetchanges,thevariableissetwith
textofwidget.

13

widthnumber

Setsthewidthforwidget.

Asimpleexampleforoptionsisshownbelow.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

84/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/wish
grid[label.myLabelbackgroundredtext"HelloWorld"reliefridgeborderwidth3]padx100pady

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

Thelistofavailablewidgetsarecategorizedbelow.

Basicwidgets
SN

Widget

Description

Label

Widgetfordisplayingsinglelineoftext.

Button

Widgetthatisclickableandtriggersanaction.

Entry

Widgetusedtoacceptasinglelineoftextasinput.

Message

Widgetfordisplayingmultiplelinesoftext.

Text

Widgetfordisplayingandoptionallyeditmultiplelinesoftext.

Toplevel

WindowwithallbordersanddecorationsprovidedbytheWindow
manager.

Layoutwidgets
SN

Widget

Description

Frame

Containerwidgettoholdotherwidgets.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

85/139

5/22/2016

TclTkQuickGuide

Place

Widgettoholdotherwidgetsinspecificplacewithcoordinatesofits
originandanexactsize.

Pack

Simplewidgettoorganizewidgetsinblocksbeforeplacingtheminthe
parentwidget.

Grid

Widgettonestwidgetspackingindifferentdirections.

Selectionwidgets
SN

Widget

Description

Radiobutton

Widgetthathasasetofon/offbuttonsandlabels,oneofwhich
maybeselected.

Checkbutton

Widgetthathasasetofon/offbuttonsandlabels,manyofwhich
maybeselected..

Menu

Widgetthatactsasholderformenuitems.

Listbox

Widgetthatdisplaysalistofcells,oneormoreofwhichmaybe
selected.

Megawidgets
SN

Widget

Description

Dialog

Widgetfordisplayingdialogboxes.

Spinbox

Widgetthatallowsuserstochoosenumbers.

Combobox

Widgetthatcombinesanentrywithalistofchoicesavailabletothe
use.

Notebook

Tabbedwidgetthathelpstoswitchbetweenoneofseveralpages,
usinganindextab.

Progressbar

Widgettoprovidevisualfeedbacktotheprogressofalong
operationlikefileupload.

Treeview

Widgettodisplayandallowbrowsingthroughahierarchyofitems
moreinformoftree.

Scrollbar

Scrollingwidgetswithoutatextorcanvaswidgets.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

86/139

5/22/2016

TclTkQuickGuide

Scale

Scalewidgettochooseanumericvaluethroughsliders.

Otherwidgets
SN

Widget

Description

Canvas

Drawingwidgetfordisplayinggraphicsandimages..

Wewillcoverabouteachofthesewidgetsinupcomingchapters.

TkBasicWidgets
BasicwidgetsarecommonwidgetsavailableinalmostallTkapplications.Thelistof
availablebasicwidgetsareasshownbelow.
1

Label

Widgetfordisplayingsinglelineoftext.

Button

Widgetthatisclickableandtriggersanaction.

Entry

Widgetusedtoacceptasinglelineoftextasinput.

Message

Widgetfordisplayingmultiplelinesoftext.

Text

Widgetfordisplayingandoptionallyeditmultiplelinesoftext.

Toplevel

Widgetusedtocreateaframethatisanewtoplevelwindow.

TkLabelWidget
AlabelwidgetisacommonwidgetusedinalmostallTkapplicationsthatisusedto
displaysimpletext.Thesyntaxforlabelwidgetisshownbelow.
labellabelNameoptions

Options
Theoptionsavailableforthelabelwidgetarelistedbelowintable.
SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

87/139

5/22/2016

TclTkQuickGuide

borderwidthwidth

Usedtodrawwithborderin3Deffects.

fontfontDescriptor

Usedtosetfontforwidget.

foregroundcolor

Usedtosetforegroundcolorforwidget.

heightnumber

Usedtosetheightforwidget.

padxnumber

Setsthepadxforthewidget.

padynumber

Setsthepadyforthewidget.

reliefcondition

Setsthe3Dreliefforthiswidget.Theconditionmay
beraised,sunken,flat,ridge,solid,orgroove.

texttext

Setsthetextforthewidget.

10

textvariablevarName

Variableassociatedwiththewidget.Whenthetextof
widgetchanges,thevariableissettotextofwidget.

11

widthnumber

Setsthewidthforwidget.

12

justifyalignment

Setsthealignmentoftextwhichcanbeleft,centeror
right.

Asimpleexampleforlabelwidgetisshownbelow.
#!/usr/bin/wish
grid[label.myLabelbackgroundredforegroundwhitetext"HelloWorld"reliefridgeborderwidth
setmyvariable"TestHello"

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

88/139

5/22/2016

TclTkQuickGuide

TkButtonWidget
Tk button widget is a clickable widget that triggers an action. The syntax for button
widgetisshownbelow.
buttonbuttonNameoptions

Options
Theoptionsavailableforthebuttonwidgetarelistedbelowintable.
SN

Syntax

Description

fontfontDescriptor

Usedtosetfontforwidget.

heightnumber

Usedtosetheightforwidget.

commandaction

Setsthecommandactionforbutton.

texttext

Setsthetextforthewidget.

widthnumber

Setsthewidthforwidget.

Asimplebuttonwidgetisshownbelow.
#!/usr/bin/wish

grid[label.myLabeltext"Clickthebuttons"textvariablelabelText]
grid[button.myButton1text"Button1"font{Helvetica18bold}height5width10command
grid[button.myButton2text"Button2"font{Helvetica18bold}height5width10command"setlabe

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

89/139

5/22/2016

TclTkQuickGuide

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

WhenweclicktheButton1,wewillgetthefollowingoutput.

WhenweclicktheButton2,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

90/139

5/22/2016

TclTkQuickGuide

TkEntryWidget
Entry widgets are used to accept a single line of text as input. Getting user input is
almostmandatoryinallTkapplications.Thesyntaxforentrywidgetisshownbelow.
entryentryNameoptions

Options
Theoptionsavailablefortheentrywidgetarelistedbelowintable.
SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

borderwidthwidth

Usedtodrawwithborderin3Deffects.

fontfontDescriptor

Usedtosetfontforwidget.

foregroundcolor

Usedtosetforegroundcolorforwidget.

padynumber

Setsthepadyforthewidget.

reliefcondition

Setsthe3Dreliefforthiswidget.Theconditionmay
beraised,sunken,flat,ridge,solid,orgroove.

textvariablevarName

Variableassociatedwiththewidget.Whenthetextof
widgetchanges,thevariableissettotextofwidget.

widthnumber

Setsthewidthforwidget.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

91/139

5/22/2016

TclTkQuickGuide

justifyside

Setsthejustificationside.Thevalidsidesareleftand
right.

10

showcharacter

Setsthecharacterforsecureentry.

Asimpleexampleusingentrywidgetisshownbelow.
#!/usr/bin/wish
grid[entry.myEntrybackgroundredforegroundwhitereliefridgeborderwidth8font{Helvetica
setmyvariable"HelloWorld"

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

Anexampleforsecureentryisshownbelow.
#!/usr/bin/wish
grid[entry.myEntrybackgroundredforegroundwhitereliefridgeborderwidth8font{Helvetica
setmyvariable"HelloWorld"

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkMessageWidget
Amessagewidgetisusedfordisplayingmultiplelinesoftext.Thesyntaxformessage
widgetisshownbelow.
messagemessageNameoptions

Options
Theoptionsavailableforthemessagewidgetarelistedbelowintable.
SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

92/139

5/22/2016

TclTkQuickGuide

borderwidthwidth

Usedtodrawwithborderin3Deffects.

fontfontDescriptor

Usedtosetfontforwidget.

foregroundcolor

Usedtosetforegroundcolorforwidget.

padxnumber

Setsthepadxforthewidget.

padynumber

Setsthepadyforthewidget.

reliefcondition

Setsthe3Dreliefforthiswidget.Theconditionmay
beraised,sunken,flat,ridge,solid,orgroove.

texttext

Setsthetextforthewidget.

textvariablevarName

Variableassociatedwiththewidget.Whenthetextof
widgetchanges,thevariableissettotextofwidget.

10

justifyalignment

Setsthealignmentoftextwhichcanbeleft,centeror
right.

11

aspectratio

Setstheaspectratioinpercent.Thedefaultis150.It
isavailablewhenwidthoptionisnotused.

12

widthnumber

Setsthewidthforwidget.

Asimpleexampleformessagewidgetisshownbelow.
#!/usr/bin/wish

grid[message.myMessagebackgroundredforegroundwhitetext"Hello\nWorld"reliefridgeborderwidth

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkTextWidget
Tk text widget is a general purpose editable text widget with features for multiple
options.Thesyntaxfortextwidgetisshownbelow.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

93/139

5/22/2016

TclTkQuickGuide

texttextNameoptions

Options
Theoptionsavailableforthetextwidgetarelistedbelowintable.
SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

borderwidthwidth

Usedtodrawwithborderin3Deffects.

fontfontDescriptor

Usedtosetfontforwidget.

foregroundcolor

Usedtosetforegroundcolorforwidget.

reliefcondition

Setsthe3Dreliefforthiswidget.Theconditionmaybe
raised,sunken,flat,ridge,solid,orgroove.

widthnumber

Setsthewidthforwidget.

heightnumber

Usedtosetheightforwidget.

Asimpleexamplefortextwidgetisshownbelow.
#!/usr/bin/wish
grid[text.myTextbackgroundredforegroundwhitereliefridgeborderwidth8padx10pady10
.myTextinsert1.0"Hello\nWorld\n"
.myTextinsertend"Anewline\n"
.myTexttagconfigureparaspacing10.15ispacing20.05i\
lmargin10.25ilmargin20.2irmargin0.25i
.myTexttagconfigurehanglmargin10.30ilmargin20.25i
.myTexttagaddpara1.02.end
.myTexttagaddhang3.03.end

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

94/139

5/22/2016

TclTkQuickGuide

As you can see, text widgets works with the help of procedures like tag, insert and
delete.Mostofthetagusageshavebeencoveredintheaboveexample.

TkTopLevelWidgets
Toplevelwidgetisusedtocreateaframethatisanewtoplevelwindow.Thesyntax
fortoplevelwidgetisshownbelow.
topleveltopLevelNameoptions

Options
Theoptionsavailableforthetoplevelwidgetarelistedbelowintable.
SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

borderwidthwidth

Usedtodrawwithborderin3Deffects.

heightnumber

Usedtosetheightforwidget.

padxnumber

Setsthepadxforthewidget.

padynumber

Setsthepadyforthewidget.

reliefcondition

Setsthe3Dreliefforthiswidget.Theconditionmaybe
raised,sunken,flat,ridge,solid,orgroove.

widthnumber

Setsthewidthforwidget.

Asimpleexamplefortoplevelwidgetisshownbelow.
#!/usr/bin/wish
toplevel.topwidth400height100backgroundredreliefridgeborderwidth8padx10pady10

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

95/139

5/22/2016

TclTkQuickGuide

AsimpleTkexampleisshownbelowusingbasicwidgets.
#!/usr/bin/wish
grid[label.myLabeltext"LabelWidget"textvariablelabelText]
grid[text.myTextwidth20height5]
.myTextinsert1.0"Text\nWidget\n"
grid[entry.myEntrytext"EntryWidget"]
grid[message.myMessagebackgroundredforegroundwhitetext"Message\nWidget"]
grid[button.myButton1text"Button"command"setlabelTextclicked"]

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkLayoutWidgets
LayoutwidgetsareusedtohandlelayoutsfortheTkapplication.Framewidgetisused
group other widgets and place, pack, and grid are layout manager to give you total
controloveryouraddingtowindows.Thelistofavailablelayoutwidgetsareasshown
below.
1

Frame

Containerwidgettoholdotherwidgets.

Place

Widgettoholdotherwidgetsinspecificplacewithcoordinatesofitsorigin
andanexactsize.

Pack

Simplewidgettoorganizewidgetsinblocksbeforeplacingtheminthe
parentwidget.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

96/139

5/22/2016

TclTkQuickGuide

Grid

Widgettonestwidgetspackingindifferentdirections.

TkFrameWidget
Theframewidgetisarectangularcontainerwidgetthatgroupswidgetsfordesigning
GUI.Thesyntaxforframewidgetisshownbelow.
frameframeNameoptions

Options
Theoptionsavailablefortheframewidgetarelistedbelowintable.
SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

borderwidthwidth

Usedtodrawwithborderin3Deffects.

heightnumber

Usedtosetheightforwidget.

padxnumber

Setsthepadxforthewidget.

padynumber

Setsthepadyforthewidget.

reliefcondition

Setsthe3Dreliefforthiswidget.Theconditionmaybe
raised,sunken,flat,ridge,solid,orgroove.

widthnumber

Setsthewidthforwidget.

Asimpleexampleforframewidgetisshownbelow.
#!/usr/bin/wish
frame.myFrame1backgroundredreliefridgeborderwidth8padx10pady10height100width
frame.myFrame2backgroundbluereliefridgeborderwidth8padx10pady10height100width
pack.myFrame1
pack.myFrame2

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

97/139

5/22/2016

TclTkQuickGuide

TkPlaceWidget
The place widget is used to locate a widget at an absolute location or a relative
locationbasedonthesizeofthewindow.Thesyntaxforplacewidgetisshownbelow.
placeplaceNameoptions

Options
Theoptionsavailablefortheplacewidgetarelistedbelowintable.
SN

Syntax

Description

xxLocation

Setstheabsolutexpositionforwidget.

yyLocation

Setstheabsoluteypositionforwidget.

relxxFraction

Setstherelativexpositionasfractionofwidthforwidget.

relyyFraction

Setstherelativeypositionasfractionofheightforwidget.

Asimpleexampleforplacewidgetisshownbelow.
#!/usr/bin/wish
.configurewidth250height300
frame.myFrame1backgroundredreliefridgeborderwidth8padx10pady10height100width
frame.myFrame2backgroundbluereliefridgeborderwidth8padx10pady10height100width
place.myFrame1x0y20
place.myFrame2x50y150

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

98/139

5/22/2016

TclTkQuickGuide

TkPackWidget
The pack widget is a rectangular container widget that groups widgets for designing
GUI.Thesyntaxforpackwidgetisshownbelow.
packpackNameoptions

Options
Theoptionsavailableforthepackwidgetarelistedbelowintable.
SN

Syntax

Description

sideside

Packsthewidgettogivensideoftheparentwindow.It
canbetop,bottom,leftandright.Thedefaultistop.

anchoredge

Packwidgetwillbeanchoredtospecificsideifthewidthis
lessthanspaceisassigned.Thevalidedgesaren,e,w,s

expandboolean

Usedtomakethewidgettheavailablespace.

padxnumber

Setsthepadxforthewidget.

padynumber

Setsthepadyforthewidget.

filldirection

Widgetmayexpandtofillextraspaceinitsparcel.The
defaultisnone.Thedirectionmaybenone,xtofill
vertically,ytofillhorizontally,bothtofillbothways.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

99/139

5/22/2016

TclTkQuickGuide

afterwidgetName

PackthiswidgetafterwidgetName,generallyontopofit.

Asimplepackexampleforpackwidgetisshownbelow.
#!/usr/bin/wish
label.label1backgroundgreentext"HelloWorld1"width30
label.label2backgroundgraytext"HelloWorld2"
frame.myFrame2backgroundbluereliefridgeborderwidth8padx10pady10height100width
pack.label1sidetopanchors
pack.label2sidetopanchors
pack.myFrame2padx10fillxsidebottomanchornafter.label2

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkGridWidget
Thegridwidgetusedtolayoutwidgetsinspecificrowsandcolumns.Thesyntaxfor
gridwidgetisshownbelow.
gridgridNameoptions

Options
Theoptionsavailableforthegridwidgetarelistedbelowintable.
SN

Syntax

Description

columnnumber

Setsthecolumnpositionforwidget.

rownumber

Setstherowpositionforwidget.

columnspannumber

Numberofcolumnstobeusedforthiswidget.Defaults
to1.

rowspannumber

Numberofrowstobeusedforthiswidget.Defaultsto

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

100/139

5/22/2016

TclTkQuickGuide

1.
5

stickyside

Setstheedgeofthecelltowhichthewidgetshould
stickto.Validvaluescanbenfortop,sforbottom,e
forright,wforleft,oracombinationoftheseletters.

Asimpleexampleforgridwidgetisshownbelow.
#!/usr/bin/wish
frame.myFrame1backgroundredreliefridgeborderwidth8padx10pady10height100width
frame.myFrame2backgroundbluereliefridgeborderwidth8padx10pady10height100width
grid.myFrame1columnspan10rowspan10stickyw
grid.myFrame2column10row2

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

AsimpleTkexampleisshownbelowforlayoutwidgets.
#!/usr/bin/wish
frame.myFrame1backgroundredreliefridgeborderwidth8padx10pady10height100width
frame.myFrame2backgroundbluereliefridgeborderwidth8padx10pady10height100width
pack.myFrame1
pack.myFrame2

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkSelectionWidget

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

101/139

5/22/2016

TclTkQuickGuide

TkSelectionWidget
Selection widgets are used to select different options in a Tk application. The list of
availableselectionwidgetsareasshownbelow.
1

Radiobutton

Widgetthathasasetofon/offbuttonsandlabels,oneofwhich
maybeselected

Checkbutton

Widgetthathasasetofon/offbuttonsandlabels,manyofwhich
maybeselected.

Menu

Widgetthatactsasholderformenuitems.

Listbox

Widgetthatdisplaysalistofcells,oneormoreofwhichmaybe
selected.

TkRadioButtonWidget
Radio button widget implements a multiplechoice button, which is a way to offer
many possible selections to the user and lets user choose only one of them. The
syntaxforradiobuttonwidgetisshownbelow.
radiobuttonradiobuttonNameoptions

Options
Theoptionsavailablefortheradiobuttonwidgetarelistedbelowintable.
SN

Syntax

Description

fontfontDescriptor

Usedtosetfontforwidget.

heightnumber

Usedtosetheightforwidget.

commandaction

Setsthecommandactionforbutton.

texttext

Setsthetextforthewidget.

widthnumber

Setsthewidthforwidget.

variablevariableName

Setsthevariableforwidget.

valuevariableValue

Setsthevariablewithvariablevalue.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

102/139

5/22/2016

TclTkQuickGuide

Asimpleradiobuttonwidgetexampleisshownbelow.
#!/usr/bin/wish

grid[frame.gender]
grid[label.myLabeltext"Male"textvariablemyLabel1]
grid[radiobutton.gender.maleBtntext"Male"variablegendervalue"Male"command"setmyLabel1Mal
grid[radiobutton.gender.femaleBtntext"Female"variablegendervalue"Female"command"setmyLabel1
.gender.maleBtnselect

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkCheckButtonWidget
Tk check button is used to create multiple selectable items in the form of check
boxes.Thesyntaxforcheckbuttonwidgetisshownbelow.
checkbuttoncheckbuttonNameoptions

Options
Theoptionsavailableforthecheckbuttonwidgetarelistedbelowintable.
SN

Syntax

Description

fontfontDescriptor

Usedtosetfontforwidget.

heightnumber

Usedtosetheightforwidget.

commandaction

Setsthecommandactionforbutton.

texttext

Setsthetextforthewidget.

widthnumber

Setsthewidthforwidget.

variablevariableName

Setsthevariableforwidget.

AsimpleTkexampleforcheckbuttonisshownbelow.
#!/usr/bin/wish
grid[label.myLabel1text"Range2030notselected"textvariablemyLabelValue1]
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

103/139

5/22/2016

TclTkQuickGuide

grid[checkbutton.chk1text"Range2030"variableoccupied1command{if{$occupied1}{
setmyLabelValue1{Range2030selected}
}else{
setmyLabelValue1{Range2030notselected}
}}]
grid[label.myLabel2text"Range30+notselected"textvariablemyLabelValue2]
grid[checkbutton.chk2text"Range2030"variableoccupied2command{if{$occupied2}{
setmyLabelValue2{Range30+selected}
}else{
setmyLabelValue2{Range30+notselected}
}}]

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

Whenweclickthecheckbutton1andcheckbutton2,wewillgetthefollowingoutput.

TkMenuWidget
TkmenuwidgetisusedalongwithTkwidgetmenubutton.So,wewillseemenubutton
first.Thesyntaxformenubuttonwidgetisshownbelow.
menubuttonmenubuttonNameoptions

MenuButtonOptions
Theoptionsavailableforthemenubuttonwidgetarelistedbelowintable.
SN

Syntax

Description

commandaction

Setsthecommandactionforbutton.

texttext

Setsthetextforthewidget.

textvariablevarName

Variableassociatedwiththewidget.Whenthetext
ofwidgetchanges,thevariableissettotextof

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

104/139

5/22/2016

TclTkQuickGuide

widget.
4

widthnumber

Setsthewidthforwidget.

menumenuName

Specifiesthenameofassociatedmenuwidget.

underlinecharPosition

Setsthepositionforhotkey.

Thesyntaxformenuisshownbelow.
menumenuNameoptions

MenuOptions
Theoptionsavailableforthemenuwidgetarelistedbelowintable.
SN

Syntax

Description

fontfontDescriptor

Usedtosetfontforwidget.

postcommandaction

Setsthecommandactiontobedonebeforeamenuis
posted.

menumenuName

Specifiesthenameofassociatedmenuwidget.

tearoffboolean

Allowsordisallowsamenutoberemovedfromthe
menubuttonanddisplayedinapermanentwindow.
Defaultisenabled.

Thesyntaxforaddingmenubuttonisshownbelow.
menuNameaddtypemenubuttonTypeoptions

Thetypeincludesseparator,cascade,checkbutton,radiobuttonandcommand.

MenuNameAddOptions
TheoptionsavailableforthemenuNameaddarelistedbelowintable.
SN

Syntax

Description

commandaction

Setsthecommandactionforthemenubutton.

menumenuName

Specifiesthenameofassociatedmenuwidget.

labelstring

Setthetextofthemenu.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

105/139

5/22/2016

TclTkQuickGuide

variablevarName

Setsthevariabletobesetwhenthisentryisselected.

valuestring

Thevalueissetforthevariable.

underlineposition

Setsthepositionforhotkey.

AsimpleTkmenuisshownbelow.
#!/usr/bin/wish

menubutton.myMenubuttonmenu.myMenubutton.myMenutext"ChangeText"
menu.myMenubutton.myMenu
.myMenubutton.myMenuaddcommandlabelHellocommand{setmyvariable"Hello"}
.myMenubutton.myMenuaddcommandlabelWorldcommand{setmyvariable"World"}
pack.myMenubutton
pack[label.myLabeltext"SelectAnoption"font{Helvetica18bold}height5width15textvariable

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

Whenweselectamenuoption,wewillgetaoutputasshownbelow.

TkListboxWidget
Tk listbox widgets are scrollable lists that can be selected. The syntax for listbox
widgetisshownbelow.
listboxbuttonNameoptions

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

106/139

5/22/2016

TclTkQuickGuide

SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

borderwidthwidth

Usedtodrawwithborderin3Deffects.

fontfontDescriptor

Usedtosetfontforwidget.

foregroundcolor

Usedtosetforegroundcolorforwidget.

heightnumberOfLines

Usedtosetnumberoflinesforheightofwidget.

selectmodemode

Modecanbesingle,browse,multipleandextended.

exportselectionbool

Tousemultiplelistboxwidgets,setthisoptionto
FALSE.ThedefaultisTRUE.

widthnumber

Setsthewidthforwidget.

Asimpleexampleforlistboxisshownbelow.
#!/usr/bin/wish
procsetLabel{text}{
.labelconfiguretext$text
}
listbox.myList
label.labeltext"NoChoiceselected"
bind.myList{setLabel[.myListgetactive]}
grid.myListrow0column0stickynews
grid.labelrow1column0columnspan2
.myListinsert0Choice1Choice2Choice3

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

Whenweselectanoption,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

107/139

5/22/2016

TclTkQuickGuide

AsimpleTkexampleisshownbelowusingselectionwidgets.
#!/usr/bin/wish

grid[frame.gender]
grid[label.label1text"Male"textvariablemyLabel1]
grid[radiobutton.gender.maleBtntext"Male"variablegendervalue"Male"command"setmyLabel1Mal
grid[radiobutton.gender.femaleBtntext"Female"variablegendervalue"Female"command"setmyLabel1
.gender.maleBtnselect
grid[label.myLabel2text"Range1notselected"textvariablemyLabelValue2]
grid[checkbutton.chk1text"Range1"variableoccupied1command{if{$occupied1}{
setmyLabelValue2{Range1selected}
}else{
setmyLabelValue2{Range1notselected}
}}]
procsetLabel{text}{
.labelconfiguretext$text
}

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkCanvasWidgets
Canvas is used for providing drawing areas. The syntax for canvas widget is shown
below.
canvascanvasNameoptions

Options
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

108/139

5/22/2016

TclTkQuickGuide

Theoptionsavailableforthecanvaswidgetarelistedbelowintable.
SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

closeenoughdistance

Setstheclosenessofmousecursortoa
displayableitem.Thedefaultis1.0pixel.This
valuemaybeafractionandmustbepositive.

scrollregionboundingBox

Theboundingboxforthetotalareaofthiscanvas.

heightnumber

Usedtosetheightforwidget.

widthnumber

Setsthewidthforwidget.

xscrollincrementsize

Theamounttoscrollhorizontallywhenscrollingis
requested.

yscrollincrementsize

Theamounttoscrollverticallywhenscrollingis
requested.

Asimpleexampleforcanvaswidgetisshownbelow.
#!/usr/bin/wish
canvas.myCanvasbackgroundredwidth100height100
pack.myCanvas

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

Widgetsfordrawingincanvas
Thelistoftheavailablewidgetsfordrawingincanvasislistedbelow.
SN

Widget

Description

Line

Drawsaline.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

109/139

5/22/2016

TclTkQuickGuide

Arc

Drawsanarc.

Rectangle

Drawsarectangle.

Oval

Drawsanoval.

Polygon

Drawsapolygon.

Text

Drawsatext.

Bitmap

Drawsabitmap.

Image

Drawsanimage.

TkCanvasLineWidget
Linewidgetisusedtodrawalineincanvas.Thesyntaxforlinewidgetisshownbelow.
canvasNamecreatelinex1y1x2y2...xnynoptions

x1y1,x2y2...xnynareusedtodeterminetheendpointsoflinesegments.

Options
Theoptionsavailableforthelinewidgetarelistedbelowintable.
SN

Syntax

Description

arrowend

Determineswhetherlineshouldhavearrowonends.
Theendcanbeboth,first,lastandnone.

fillcolor

Thefillcolorfillsthelinesegmentwiththecolor.

smoothboolean

Thiscanbesettotruemakethelinesegmentstobe
renderedwithasetofBeziersplines.

splinestepsnumber

Determinesthenumberoflinesegmentforbezier
splines.

Asimpleexampleforlinewidgetisshownbelow.
#!/usr/bin/wish
canvas.myCanvasbackgroundredwidth100height100
pack.myCanvas
.myCanvascreateline1010505030100arrowbothfillyellowsmoothtruesplinesteps2
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

110/139

5/22/2016

TclTkQuickGuide

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkCanvasArcWidget
Arcwidgetisusedtodrawaarcincanvas.Thesyntaxforarcwidgetisshownbelow.
canvasNamecreatearcx1y1x2y2options

x1y1,x2y2aretheendpointsofarc.

Options
Theoptionsavailableforthearcwidgetarelistedbelowintable.
SN

Syntax

Description

fillcolor

Thefillcolorfillsthearcwiththecolor.

startangle

Thestartlocationindegreesforthisarc.Thedefaultis0.

extentangle

Thenumberofdegreestoextendthearcfromthestart
position.Thedefaultis90degrees.

stylestyleType

Thestyleofarctodraw.Theoptionsarepieslice,chordand
arc.

Asimpleexampleforarcwidgetisshownbelow.
#!/usr/bin/wish
canvas.myCanvasbackgroundredwidth100height100
pack.myCanvas
.myCanvascreatearc10108080fillyellow

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

111/139

5/22/2016

TclTkQuickGuide

TkCanvasRectangleWidget
Rectangle widget is used to draw a rectangle shape in canvas. The syntax for
rectanglewidgetisshownbelow.
canvasNamecreaterectanglex1y1x2y2options

x1y1,x2y2aretheendpointsofrectangle.

Options
Theoptionsavailablefortherectanglewidgetarelistedbelowintable.
SN

Syntax

Description

outlinecolor

Determinestheoutlinecolor.

fillcolor

Thefillcolorfillstheovalwiththecolor.

stipplebitmap

Thestipplepatterntouseifthefilloptionisbeingused.

widthnumber

Determinesthewidth.

Asimpleexampleforrectanglewidgetisshownbelow.
#!/usr/bin/wish
canvas.myCanvasbackgroundredwidth200height200
pack.myCanvas
.myCanvascreaterectangle505010080fillyellow

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

112/139

5/22/2016

TclTkQuickGuide

TkCanvasOvalWidget
Oval widget is used to draw a oval shape in canvas. The syntax for oval widget is
shownbelow.
canvasNamecreateovalx1y1x2y2options

x1y1,x2y2aretheendpointsofoval.

Options
Theoptionsavailablefortheovalwidgetarelistedbelowintable.
SN

Syntax

Description

outlinecolor

Determinestheoutlinecolor.

fillcolor

Thefillcolorfillstheovalwiththecolor.

stipplebitmap

Thestipplepatterntouseifthefilloptionisbeingused.

widthnumber

Determinesthewidth.

Asimpleexampleforovalwidgetisshownbelow.
#!/usr/bin/wish
canvas.myCanvasbackgroundredwidth200height200
pack.myCanvas
.myCanvascreateoval505010080fillyellow

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

113/139

5/22/2016

TclTkQuickGuide

TkCanvasPolygonWidget
Polygon widget is used to draw a polygon shape in canvas. The syntax for polygon
widgetisshownbelow.
canvasNamecreatepolygonx1y1x2y2...xnynoptions

x1y1,x2y2...xnynareusedtodeterminetheendpointsofpolygon.

Options
Theoptionsavailableforthepolygonwidgetarelistedbelowintable.
SN

Syntax

Description

outlinecolor

Determinestheoutlinecolor.

fillcolor

Thefillcolorfillstheovalwiththecolor.

stipplebitmap

Thestipplepatterntouseifthefilloptionisbeing
used.

widthnumber

Determinesthewidth.

smoothboolean

Thiscanbesettotruemakethelinesegmentstobe
renderedwithasetofBeziersplines.

splinestepsnumber

Determinesthenumberoflinesegmentforbezier
splines.

Asimpleexampleforpolygonwidgetisshownbelow.
#!/usr/bin/wish
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

114/139

5/22/2016

TclTkQuickGuide

canvas.myCanvasbackgroundredwidth200height200
pack.myCanvas
.myCanvascreatepolygon505010080120120100190fillyellowoutlinegreen

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkCanvasTextWidget
Canvastextwidgetisusedtodrawtextincanvas.Thesyntaxforcanvastextwidget
isshownbelow.
canvasNamecreatetextxyoptions

xandyareusedtodeterminethepositionoftext.

Options
Theoptionsavailableforthecanvastextwidgetarelistedbelowintable.
SN

Syntax

Description

anchorposition

Thetextwillbepositionedrelativetothexandylocations.
Centerisdefaultandotheroptionsaren,s,e,w,ne,se,sw
andnw.

justifystyle

Determinesthemultilineshouldberightjustified,left
justified,orcenterjustified.Thedefaultisleft.

fillcolor

Thefillcolorfillstheovalwiththecolor.

texttext

Thetextfortextwidget.

fontfontStyle

Thefonttouseforthistext.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

115/139

5/22/2016

TclTkQuickGuide

Asimpleexampleforcanvastextwidgetisshownbelow.
#!/usr/bin/wish
canvas.myCanvasbackgroundredwidth200height200
pack.myCanvas
.myCanvascreatetext100100fillyellowjustifycentertext"HelloWorld.\nHowareyou?"font

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkCanvasBitmapWIdget
Bitmap widget is used to add bitmap to canvas. The syntax for bitmap widget is
shownbelow.
canvasNamecreatebitmapxyoptions

xandysetthelocationofbitmap.

Options
Theoptionsavailableforthebitmapwidgetarelistedbelowintable.
SN

Syntax

Description

anchorposition

Thebitmapwillbepositionedrelativetothexandy
locations.Centerisdefaultanotheroptionsaren,s,e,w,
ne,se,swandnw.

bitmapname

Definesthebitmaptodisplay.TheavailablebitmapsinTk
includewarning,question,questhead,info,hourglass,error,
gray12,gray25,gray50andgray75.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

116/139

5/22/2016

TclTkQuickGuide

Asimpleexampleforbitmapwidgetisshownbelow.
#!/usr/bin/wish
canvas.myCanvasbackgroundredwidth100height100
pack.myCanvas
.myCanvascreatebitmap5050bitmapinfo

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkCanvasImageWidget
Imagewidgetisusedcreateadisplayedimageitem.Animagecanbecreatedfroma
GIF, PNG, PPM, PGM, or XBitmap image. The syntax for image widget is shown
below.
canvasNamecreateimagexyoptions

xandysetthelocationofbitmap.

Option
Theoptionavailablefortheimagewidgetarelistedbelowintable.
SN

Syntax

Description

imageimageName

Thevariablethatholdsimagetodisplay.

Asimpleexampleforimagewidgetisshownbelow.
#!/usr/bin/wish
canvas.myCanvasbackgroundredwidth100height100
pack.myCanvas
setmyImage[imagecreatephoto]
$myImageread"/Users/myImages/myImage1.png"
.myCanvascreateimage5050image$myImage

Whenweruntheaboveprogram,wewillgetthefollowingoutput.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

117/139

5/22/2016

TclTkQuickGuide

Anexampleusingdifferentcanvaswidgetsisshownbelow.
#!/usr/bin/wish
canvas.myCanvasbackgroundredwidth200height200
pack.myCanvas
.myCanvascreatearc10105050fillyellow
.myCanvascreateline1030505010010arrowbothfillyellowsmoothtruesplinesteps2
.myCanvascreateoval505010080fillyellow
.myCanvascreatepolygon5015010080120120100190fillyellowoutlinegreen
.myCanvascreaterectangle150150170170fillyellow
.myCanvascreatetext17020fillyellowtext"Hello"font{Helvetica18bold}
.myCanvascreatebitmap18050bitmapinfo

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkMegaWidgets
Mega widgets include many complex widgets which is often required in some large
scaleTkapplications.Thelistofavailablemegawidgetsareasshownbelow.
SN

Widget

Description

Dialog

Widgetfordisplayingdialogboxes.

Spinbox

Widgetthatallowsuserstochoosenumbers.

Combobox

Widgetthatcombinesanentrywithalistofchoicesavailabletothe
use.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

118/139

5/22/2016

TclTkQuickGuide

Notebook

Tabbedwidgetthathelpstoswitchbetweenoneofseveralpages,
usinganindextab.

Progressbar

Widgettoprovidevisualfeedbacktotheprogressofalong
operationlikefileupload.

Treeview

Widgettodisplayandallowbrowsingthroughahierarchyofitems
moreinformoftree.

Scrollbar

Scrollingwidgetswithoutatextorcanvaswidgets.

Scale

Scalewidgettochooseanumericvaluethroughsliders.

TkDialogWidget
Adialogwidgetisusedfordisplayingdialogboxes.
tk_dialogwindowtitledetailTextbitmapdefaultstring1...stringn

The use of each of the above option of the widget is listed below in table and they
needtousedinthesameorder.
SN

Syntax

Description

window

Determinesthenameoftoplevelwindowfordialogandany
existingwindowbythisnameisdestroyed.

title

Titleforthewidget.

detailText

Detailtextforthewidget.

bitmap

Bitmap(intheformsuitableforTk_GetBitmap)todisplayin
thetopportionofthedialog,totheleftofthetext.Ifthisis
anemptystringthennobitmapisdisplayedinthedialog.
TheavailablebitmapsinTkincludewarning,question,
questhead,info,hourglass,error,gray12,gray25,gray50
andgray75.

default

Theindexofbuttontobeselected.

string1...stringn

Thestringsforbuttonsanditdeterminesthenumberof
buttons.

Asimpleexamplefordialogwidgetisshownbelow.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

119/139

5/22/2016

TclTkQuickGuide

#!/usr/bin/wish
seta[tk_dialog.myDialog"myTitle""myDetailText"questhead0"Yes""No"]

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkSpinboxWidget
Spinbox widget allows users to choose numbers or arbitrary values. The syntax for
spinboxwidgetisshownbelow.
spinboxspinboxNameoptions

Options
Theoptionsavailableforthespinboxwidgetarelistedbelowintable.
SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

borderwidthwidth

Usedtodrawwithborderin3Deffects.

fontfontDescriptor

Usedtosetfontforwidget.

foregroundcolor

Usedtosetforegroundcolorforwidget.

fromnumber

Rangestartvalueforspinbox.

incrementnumber

Rangeincrementvalueforspinbox.

reliefcondition

Setsthe3Dreliefforthiswidget.Theconditionmay
beraised,sunken,flat,ridge,solid,orgroove.

textvariablevarName

Variableassociatedwiththewidget.Whenthetextof
widgetchanges,thevariableissettotextofwidget.

tonumber

Rangeendvalueforspinbox.

10

valuesarray

Arbitraryvaluesforspinboxwidget.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

120/139

5/22/2016

11

TclTkQuickGuide

widthnumber

Setsthewidthforwidget.

Asimpleexampleforspinboxwidgetisshownbelow.
#!/usr/bin/wish

setmylist[listCC++LuaTcl]
pack[spinbox.s1textvariablespinval1values$mylistbackgroundyellowborderwidth5font{
pack[spinbox.s2textvariablespinval2from1.0to100.0increment5backgroundyellowborderwidth

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkComboboxWIdget
Comboboxwidgetisawidgetthatcombinesanentrywithalistofchoicesavailableto
theuse.Thesyntaxforcomboboxwidgetisshownbelow.
comboboxcomboboxNameoptions

Options
Theoptionsavailableforthecomboboxwidgetarelistedbelowintable.
SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

borderwidthwidth

Usedtodrawwithborderin3Deffects.

fontfontDescriptor

Usedtosetfontforwidget.

foregroundcolor

Usedtosetforegroundcolorforwidget.

textvariablevarName

Variableassociatedwiththewidget.Whenthetext
ofwidgetchanges,thevariableissettotextof
widget.

valuesarray

Arbitraryvaluesforcomboboxwidget.

widthnumber

Setsthewidthforwidget.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

121/139

5/22/2016

TclTkQuickGuide

justifyalignment

Setsthealignmentoftextwhichcanbeleft,center
orright.

staterequiredState

Setsthestatewhichcanbereadonly,disabledor
normal.

10

postcommandcommand

Proceduretobeexecutedpostaction.

Asimpleexampleforcomboboxwidgetisshownbelow.
#!/usr/bin/wish
setmylist[listCC++LuaTcl]
pack[ttk::combobox.s1textvariablecombovaluevalues$mylistbackgroundyellowfont{Helvetica
setcombovalue"C"

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkNotebookWidget
A tabbed widget that helps to switch between one of several pages, using an index
tab.Thesyntaxfornotebookwidgetisshownbelow.
ttk::notebooknotebookNameoptions

Options
Theoptionsavailableforthenotebookwidgetarelistedbelowintable.
SN

Syntax

Description

heightnumber

Usedtosetheightforwidget.

widthnumber

Setsthewidthforwidget.

Asimpleexamplefornotebookwidgetisshownbelow.
#!/usr/bin/wish
ttk::notebook.nwidth100height100
ttk::frame.n.f1;
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

122/139

5/22/2016

TclTkQuickGuide

ttk::frame.n.f2;
.nadd.n.f1text"TabOne"
.nadd.n.f2text"TabTwo"
pack[label.n.f1.f2backgroundredforegroundwhitetext"TabOne"]
pack[label.n.f2.f2backgroundredforegroundwhitetext"TabTwo"]
pack.n

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

Theprocedureaddisusedtoaddframestothenotebookwidgetasshownabove.

TkProgressbarWidget
Progressbar widget is used to provide visual feedback of the progress of a long
operationlikefileupload.Thesyntaxforprogressbarwidgetisshownbelow.
progressbarprogressbarNameoptions

Options
Theoptionsavailabletoprogressbarwidgetislistedbelowintable.
SN

Syntax

Description

lengthnumber

Setsthelengthforwidget.

maximumnumber

Setthemaximumpossiblevalue.Defaultis100.

modemode

Modecanbeindeterminateordeterminate.

orienorientation

Setstheorientationforwidget.Itcanbeeitherhorizontal
andvertical.

valuenumber

Thecurrentprogressoftheprogressbar.

variablevarName

Variableassociatedwiththewidget.Whenthetextof
widgetchanges,thevariableissettotextofwidget.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

123/139

5/22/2016

TclTkQuickGuide

Asimpleexampleforprogressbarwidgetisshownbelow.
#!/usr/bin/wish
pack[ttk::progressbar.p1orienthorizontallength200modeindeterminatevalue90]
pack[ttk::progressbar.p2orienthorizontallength200modedeterminatevariableamaximum75

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkTreeview
Treeview widget is used to choose a numeric value through sliders. The syntax for
treeviewwidgetisshownbelow.
treeviewtreeviewNameoptions

Options
Theoptionsavailableforthetreeviewwidgetarelistedbelowintable.
SN

Syntax

Description

columnscolumnNames

Anarrayofcolumnnamesforwidget.

displaycolumnscolumns

Anarrayofcolumnnamesorindicesspecifying
columnstobedisplayed.Use#allforall.

heightnumber

Heightforwidget.

selectmodemode

Selectionmodewhichcanbeextended,browse,or
none.

Asimpleexamplefortreeviewwidgetisshownbelow.
#!/usr/bin/wish
ttk::treeview.treecolumns"CreatorYear"displaycolumns"YearCreator"
.treeheadingCreatortext"Creator"anchorcenter
.treeheadingYeartext"Year"anchorcenter
pack.tree
.treeinsert{}endidLanguagestext"Languages"
.treeinsertLanguagesendtextCvalues[list"DennisRitchie""1990"]
.treeinsert""endidDirecttext"Direct"
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

124/139

5/22/2016

TclTkQuickGuide

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

Tomovetheelements,wecanusethefollowingcommand.
.treemoveLanguagesDirectend

Wewillgetthefollowingoutputwhentheabovecommandisexecuted.

Similarly,wecanusethedeletecommandtodeleteavaluesfromtreeview.

TkScrollbarWidget
Scrollbarwidgetisascrollingwidgetthatcanworkwithoutatextorcanvaswidgets.
Thesyntaxforscrollbarwidgetisshownbelow.
scrollbarscrollbarNameoptions

Options
Theoptionsavailableforthescrollbarwidgetarelistedbelowintable.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

125/139

5/22/2016

TclTkQuickGuide

SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

borderwidthwidth

Usedtodrawwithborderin3Deffects.

orienorientation

Setstheorientationforwidget.Itcanbeeither
horizontalandvertical.

reliefcondition

Setsthe3Dreliefforthiswidget.Theconditionmaybe
raised,sunken,flat,ridge,solid,orgroove.

commandcommand

Commandlinksviewtoscrollbarwidget.

Asimpleexampleforscrollbarwidgetisshownbelow.
#!/usr/bin/wish

grid[tk::listbox.lyscrollcommand".s1set"xscrollcommand".s2set"height5width20]column
grid[ttk::scrollbar.s1command".lyview"orientverticalbackgroundyellowborderwidth5reliefrid
grid[ttk::scrollbar.s2command".lxview"orienthorizontalbackgroundyellowborderwidth5
for{setindex0}{$index<100}{incrindex}{
.linsertend"Alonglineoftextfortestingscrollbar."
}

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkScaleWidget
Scalewidgetisusedtochooseanumericvaluethroughsliders.Thesyntaxforscale
widgetisshownbelow.
scalescaleNameoptions

Options
Theoptionsavailableforthescalewidgetarelistedbelowintable.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

126/139

5/22/2016

TclTkQuickGuide

SN

Syntax

Description

backgroundcolor

Usedtosetbackgroundcolorforwidget.

borderwidthwidth

Usedtodrawwithborderin3Deffects.

fontfontDescriptor

Usedtosetfontforwidget.

foregroundcolor

Usedtosetforegroundcolorforwidget.

fromnumber

Rangestartvalueforwidget.

variablevarName

Variableassociatedwiththewidget.Whenthetextof
widgetchanges,thevariableissettotextofwidget.

lengthnumber

Setsthelengthforwidget.

orienorientation

Setstheorientationforwidget.Itcanbeeither
horizontalandvertical.

reliefcondition

Setsthe3Dreliefforthiswidget.Theconditionmaybe
raised,sunken,flat,ridge,solid,orgroove.

10

tonumber

Rangeendvalueforwidget.

11

commandcommand

Proceduretobeexecutedonaction.

Asimpleexampleforscalewidgetisshownbelow.
#!/usr/bin/wish
procscaleMe{mywidgetscaleValue}{

$mywidgetconfigurelength$scaleValue
}
pack[scale.s2from100.0to200.0length100backgroundyellowborderwidth5font{Helvetica

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

Whenwescrollthescaletomaximum,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

127/139

5/22/2016

TclTkQuickGuide

AsimpleTkexampleisshownbelowusingsomemegawidgets.
#!/usr/bin/wish
ttk::treeview.treecolumns"CreatorYear"displaycolumns"YearCreator"
.treeheadingCreatortext"Creator"anchorcenter
.treeheadingYeartext"Year"anchorcenter
pack.tree
.treeinsert{}endidLanguagestext"Languages"
.treeinsertLanguagesendtextCvalues[list"DennisRitchie""1990"]
procscaleMe{mywidgetscaleValue}{

$mywidgetconfigurelength$scaleValue
}
pack[scale.s2from100.0to200.0length100backgroundyellowborderwidth5font{Helvetica
pack[ttk::progressbar.p1orienthorizontallength200modeindeterminatevalue90]
pack[ttk::progressbar.p2orienthorizontallength200modedeterminatevariableamaximum75

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

TkFonts
Thereareanumberofwidgetsthatsupportsdisplayingtext.Mostoftheseprovides
theoptionoffontattribute.Thesyntaxforcreatingafontisshownbelow.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

128/139

5/22/2016

TclTkQuickGuide

fontcreatefontNameoptions

Options
Theoptionsavailableforthefontcreatearelistedbelowintable.
SN

Syntax

Description

familyfamilyName

Thenameoffontfamily.

sizenumber

Thesizeoffont.

weightlevel

Theweightforfont.

Asimpleexampleforfontcreationisshownbelow.
#!/usr/bin/wish
fontcreatemyFontfamilyHelveticasize18weightbold
pack[label.myLabelfontmyFonttext"HelloWorld"]

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

Togetallthefontsavailable,wecanusethefollowingcommand.
#!/usr/bin/wish
puts[fontfamilies]

Whenweruntheabovecommand,wewillgetthefollowingoutput.
{AbadiMTCondensedExtraBold}{AbadiMTCondensedLight}{AlBayan}{AlNile}{AlTarikh}{American

TkImages
Theimagewidgetisusedtocreateandmanipulateimages.Thesyntaxforcreating
imageisasfollows.
imagecreatetypenameoptions

Intheabovesyntaxtypeisphotoorbitmapandnameistheimageidentifier.
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

129/139

5/22/2016

TclTkQuickGuide

Options
Theoptionsavailableforimagecreatearelistedbelowintable.
SN

Syntax

Description

filefileName

Thenameoftheimagefilename.

heightnumber

Usedtosetheightforwidget.

widthnumber

Setsthewidthforwidget.

datastring

Imageinbase64encodedstring.

Asimpleexampleforimagewidgetisshownbelow.
#!/usr/bin/wish
imagecreatephotoimgobjfile"/Users/rajkumar/Desktop/FDrive/pictur/vb/Forests/680049.png"width
pack[label.myLabel]
.myLabelconfigureimageimgobj

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

130/139

5/22/2016

TclTkQuickGuide

Theavailablefunctionforimagearelistedbelowintable.
SN

Syntax

Description

imagedeleteimageName

Deletestheimagefrommemoryandrelated
widgetsvisually.

imageheightimageName

Returnstheheightforimage.

imagewidthimageName

Returnsthewidthforimage.

imagetypeimageName

Returnsthetypeforimage.

imagenames

Returnsthelistofimagesliveinmemory.

Asimpleexampleforusingtheaboveimagewidgetcommandsisshownbelow.
#!/usr/bin/wish
imagecreatephotoimgobjfile"/Users/rajkumar/images/680049.png"width400height400
pack[label.myLabel]
.myLabelconfigureimageimgobj
puts[imageheightimgobj]
puts[imagewidthimgobj]
puts[imagetypeimgobj]
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

131/139

5/22/2016

TclTkQuickGuide

puts[imagenames]
imagedeleteimgobj

The image will be deleted visually and from memory once "image delete imgobj"
commandexecutes.Inconsole,theoutputwillbelikethefollowing.
400
400
photo
imgobj::tk::icons::information::tk::icons::error::tk::icons::warning::tk::icons::question

TkEvents
Eventsinitssimplestformishandledwiththehelpofcommands.Asimpleexample
foreventhandlingiseventhandlingwithbuttonandisshownbelow.
#!/usr/bin/wish
procmyEvent{}{
puts"Eventtriggered"
}
pack[button.myButton1text"Button1"commandmyEvent]

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

Asimpleprogramtoshowdelaytextanimationeventisshownbelow.
#!/usr/bin/wish
procdelay{}{
for{setj0}{$j<100000}{incrj}{
}
}
label.myLabeltext"Hello................"width25
pack.myLabel
setstr"Hello................"
for{seti[stringlength$str]}{$i>2}{seti[expr$i1]}{
.myLabelconfiguretext[stringrange$str0$i]
update
delay
}

Whenweruntheprogram,wewillgetthefollowingoutputinanimatedway.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

132/139

5/22/2016

TclTkQuickGuide

Eventafterdelay
Thesyntaxforeventafterdelayisshownbelow.
aftermillisecondsnumbercommand

Asimpleprogramtoshowafterdelayeventisshownbelow.
#!/usr/bin/wish
procaddText{}{
label.myLabeltext"Hello................"width25
pack.myLabel
}
after1000addText

Whenweruntheprogram,wewillgetthefollowingoutputinafteronesecond.

Youcancancelaneventusingtheaftercancelcommandasshownbelow.
#!/usr/bin/wish
procaddText{}{
label.myLabeltext"Hello................"width25
pack.myLabel
}
after1000addText
aftercanceladdText

EventBinding
Thesyntaxforeventbindingisasshownbelow.
bindarguments

Keyboardeventsexample
#!/usr/bin/wish
bind.{puts"KeyPressed:%K"}

WhenweruntheprogramandpressaletterXwewillgetthefollowingoutput.
KeyPressed:X
http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

133/139

5/22/2016

TclTkQuickGuide

Mouseeventsexample
#!/usr/bin/wish
bind.{puts"Button%bPressed:%x%y"}

When we run the program and press the left mouse button we will get an output
similartofollowing.
Button1Pressed:8990

Linkingeventswithbuttonexample
#!/usr/bin/wish
procmyEvent{}{
puts"Eventtriggered"
}
pack[button.myButton1text"Button1"commandmyEvent]
bind.".myButton1invoke"

Whenweruntheprogramandpressenterwewillgetthefollowingoutput.
Eventtriggered

TkWindowsManager
Window manager is used to handle the top level window. It helps in controlling the
size, position and other attributes of the window. In Tk, . is used to refer the main
window.Thesyntaxforwindowcommandisshownbelow.
wmoptionwindowarguments

ThelistofoptionsavailableforTkwmcommandisshowninfollowingtable.
SN

Syntax

Description

aspectwindowNameabcd

Trytomaintaintheratioofwidth/height
tobebetweena/bandc/d.

geometrywindowName
geometryParams

Usedtosetgeometryforwindow.

gridwindowNamewhdxdy

Setsthegridsize.

groupwindowNameleaderName

leaderNamegivestheleaderofagroupof

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

134/139

5/22/2016

TclTkQuickGuide

relatedwindows.
5

deiconifywindowName

Bringsthescreentonormalifminimized.

iconifywindowName

Minimizesthewindow.

statewindowName

Returnsthecurrentstateofwindow.

withdrawwindowName

Unmapsthewindowandremovesits
detailsinmemory.

iconbitmapwindowNameimage

Setsorreturnstheiconbitmap.

10

iconPhotowindowNameimage

Setsorreturnstheiconphoto.

11

commandwindowName
commandString

Recordthestartupcommandinthe
WM_COMMANDproperty.

12

protocolwindowNamearguments

Registeracommandtohandlethe
protocolrequestname,whichcanbe
WM_DELETE_WINDOW,
WM_SAVE_YOURSELF,WM_TAKE_FOCUS.
Eg:wmprotocol.WM_DELETE_WINDOW
Quit

13

minsizewindowNamesize

Determinestheminimumwindowsize.

14

maxsizewindowNamesize

Determinesthemaximumwindowsize.

15

titlewindowNametitleText

Determinesthetitleforwindow.

16

attributessubOptions

Therearelotofattributesavailablelike
alpha,fullscreenandsoon.

Someoftheabovecommandsareusedinthefollowingexample.
#!/usr/bin/wish
wmmaxsize.800800
wmminsize.300300
wmtitle."Hello"
wmattributes.alpha".90"
wmgeometry.300x200+100+100

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

135/139

5/22/2016

TclTkQuickGuide

As you can see alpha is one of the attributes available. The list of commonly used
subcommandsarelistedbelow.
SN

Syntax

Description

alphanumber

Setsthealphaforwindow.

fullscreennumber

Numbercanbe0fornormalscreenor1forfullscreen.

topmostnumber

Setsorreturnwhetherwindowistopmost.Valuecanbe0
or1.

CreatingWindow
Wecanusetoplevelcommandtocreateanwindowandanexampleisshownbelow.
#!/usr/bin/wish
toplevel.t

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

136/139

5/22/2016

TclTkQuickGuide

DestroyingWindow
Wecanusedestroycommandtodestroyanwindowandanexampleisshownbelow.
#!/usr/bin/wish
destroy.t

Theabovecommandwilldestroywindownamed.t.

TkGeometryManager
The geometry manager is used to manage the geometry of the window and other
frames. We can use it handle the position and size of the window and frames. The
layoutwidgets

areusedforthispurpose.

Positioningandsizing
Thesyntaxforpositioningandsizingwindowisshownbelow.
wmgeometry.wxh+/x+/y

Here w refers to width and h refers to height. It is followed by a '+' or '' sign with
numbernextreferringtothexpositiononscreen.Similarlythefollowing'+'or''sign
withnumberreferstotheypositiononscreen
Asimpleexampleisshownbelowfortheabove.
#!/usr/bin/wish
wmgeometry.300x200+100+100

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

137/139

5/22/2016

TclTkQuickGuide

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

GridGeometry
Thesyntaxforgridgeometryisshownbelow.
gridgridNamecolumnnumberrownumbercolumnspannumberrowspannumber

Thecolumn,row,columnspan,rowspanhelpsinprovidingthegridgeometry.
Asimpleexampleisshownbelowfortheabove.
#!/usr/bin/wish
frame.myFrame1backgroundredheight100width100
frame.myFrame2backgroundblueheight100width50
grid.myFrame1columnspan10rowspan10stickyw
grid.myFrame2column10row2

Whenweruntheaboveprogram,wewillgetthefollowingoutput.

PreviousPage

NextPage
Advertisements

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

138/139

5/22/2016

TclTkQuickGuide

Write for us

FAQ's

Helping

Contact

Copyright 2016. All Rights Reserved.


Enter email for newsletter

http://www.tutorialspoint.com/tcltk/tcl_tk_quick_guide.htm

go

139/139

Potrebbero piacerti anche