1 / 27

Tcl / Tk Tutorial

Tcl / Tk Tutorial. Dongsoo S. Kim dskim@iupui.edu. What is Tcl / Tk ?. Tcl : T ool C ommand L anguage Interpreted programming (scripting) language Build on-the-fly commands and procedures Embeddable Platform-independent Tk : GUI toolkit and widgets based on Tcl

dawson
Download Presentation

Tcl / Tk Tutorial

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Tcl/TkTutorial Dongsoo S. Kim dskim@iupui.edu

  2. What is Tcl/Tk? • Tcl: Tool Command Language • Interpreted programming (scripting) language • Build on-the-fly commands and procedures • Embeddable • Platform-independent • Tk: • GUI toolkit and widgets based on Tcl • Open source, cross-platform

  3. Why Tcl/TK? • Easy and fast programming • Free • Lots of online documentation, mostly free • Resources • http://www.tcl.tk • Major applications use the Tcl as their interfaces: • Ns2 • Mentor Graphics

  4. Hello World 115.145.171.157 > tcl % puts "Hello. World!" Hello. World! % exit >

  5. Script File • Start the Tcl program followed by a filename containing the script. > cat hello.tcl puts "Hello. World!" > tcl hello.tcl Hello. World! >

  6. Script as a Program • A script text file can be considered as a program if • it is an executable file, and • its first line contains a full path name of the tcl program following “#!” > ls -l -rwxr-xr-x 1 user group 42 Jul 3 13:12 hello.tcl > which tcl /usr/local/bin/tcl > cat hello.tcl #!/usr/local/bin/tcl puts "Hello. World!" > hello.tcl Hello. World! >

  7. Tcl Syntax • Simple syntax • command_name arg1 arg2 … • Print to screen (puts) % puts –nonewline"Hello. " % puts "World!" • Assignment (set) % set income 32000 % puts "The income is $income" • Use '$' to get the value of a variable (R-value)

  8. Comments • A line started with a pond sign(#) is ignored as comments until the end of the line • A command can be followed by a comment in a line with by placing ;# • Exception • #! at the first line indicates the script program • It is a Unix rule, but not a Tcl rule # the first script puts –nonewline"Hello. " ;# continuing puts "World!“

  9. Multiple Commands in a Line • A Tcl command is terminated by an invisible new line character, or • A semicolon(;) can be used to explicitly terminate a command % puts "Hello. "; puts "World! " hello world

  10. A Command Stretched to Lines • A command can be stretched to multiple lines by using backslashes (\) • The backslash and a following new line character is ignored • Note: There must not be any characters (even space characters) between the backslash and the new line character % puts -nonewline \ =>"Hello. World!" Hello. World!tcl>

  11. Mathematical Expression % set pi 3.141592 % set r 2 % expr2*$pi*$r 12.566368 % exprsin($pi/3) 0.866025294853 • Mathematical expression command (expr) • Operators • arithmetic (+, -, *, /, %) • Bitwise (~, <<, >>, &, ^, |) • Logical (!, &&, ||) • Boolean (<, >, <=, >=, ==, !=) • String Boolean (eq, ne, <, >, <=, >=) • List containment (in, ni) • Ternary (x?y:z) • Math functions (log, sin, cos, …)

  12. Sub-Command Evaluation % set a 3.0 % set b $a+4 % puts $b 3.0+4 % set c [expr $a+4] % puts $c 7.0 • A Tcl command in a Tcl command: []

  13. Control Structures (if) set sel 3 if {$sel == 1} { puts "Selection $sel" } elseif {$sel == 2} { puts "Selection $sel" } else { puts "Invalid selection" } • if {cond} {commands}[ elseif {cond} {commands} …][ else {commands} ]

  14. Control Structures (while) set i 1 set sum 0 while {$i <= 10} { set sum [expr $sum+$i] incri } while {cond} {commands}

  15. Control Structures (for) puts "Fahrenheit\tCelcius" for {set fahr 0} {$fahr < 100} {incrfahr} { set celc [expr 5*($fahr-32)/9] puts "$fahr\t\t$celc" } Fahrenheit Celcius 0 -18 1 -182 -17 … for {init} {term} {incr} {statements}

  16. Control Structures (foreach) • Basic foreachset weekdays {Sun Mon Tue Wed Thu Fri Sat}foreach d $weekdays { puts $d} • foreach Variationsset Colors {red orange yellow green blue purple}foreach {a b c} $Colors { puts "$c--$b--$a“}set Foods {apple orange banana lime berry grape}foreach f $Foods c $Colors { puts "a $f is usually $c" } foreach {a b} $Foods c $Colors { puts "$a & $b are foods. $c is a color." }

  17. Procedures proc mile2km dist { return [expr $dist*1.6] } puts "Miles \t KM" for {set d 1} {$d < 10} {incr d} { set km [mile2km $d] puts "$d\t $km" } • Called by value only • Syntaxprocname arg-list proc-body

  18. Variable scope • set a 5 set b 6 set c 7 proc var_scope { } { global a set a 3 set b 2 set ::c 1 } var_scope puts "The value for a b c is: $a $b $c" By default, all variables in a procedure are local. To access the variable outside of the scope, use the command “global”.

  19. Lists in Tcl • set my_list [list a b c] set my_list "a b c " set my_list {a b c} An ordered collection of elements A string containing any number of elements separated by white spaces (space or tab characters). For example, Sun Mon Tue Wed Thu Fri Satis a list with seven elements. To save a list to a variable

  20. List Operations concat – join multiple list into a single list join – concatenate list elements into a string lappend – append elements to an existing list lindex – return an indexed element from a list linsert – insert an element to an existing list list – create explicitly a list from values llength – return the number of elements in a list lrange – return a sub-list from a list lreplace – return a new list after replacing elements lsearch – return the index of a searching pattern lsort – sort the list split – return a list by splitting a string by a split-char.

  21. List Operations, Example set weekday [list “Mon” “Tue” “Wed” “Thu” “Fri”] set weekend {Sat Sun} set week [concat $weekday $weekend] puts $week • Mon Tue Wed Thu Fri Sat Sun lindex $week 0 • Mon • lindex $week end • Sun • llength $weekday • 5

  22. Lists of lists (of lists…) set a [list [list x y z]] puts [lindex $a 0] puts [lindex [lindex $a 0] 1] puts [lindex [lindex $a 1] 0] (unexpected result) set a [list x [list [list y] [list z]]] => How to get to the z? set arg1 [list g [list f [list h [list i X]]] [list r Y] k] set arg2 [list g [list f [list h [list i Y]]] [list r b] L] set both [list $arg1 $arg2] puts $both

  23. Array operations Associative arrays (string as index) set color(rose) red set color(sky) blue set color(medal) gold set color(leaves) green set color(blackboard) black puts [array exists color](tests if an array with the name "color" exists) puts [array exists colour] puts [array names color] (returns a list of the index strings) foreach item [array names color] { puts "$item is $color($item)" } (iterating through array) set lstColor [array get color] (convert array to list) array set color $lstColor (convert list to array)

  24. Regular expressions • regsubset stmt "Fan is one of Shania’s fans" regsub –nocase"fan" $stmt "Kristy"newStmt ?switches? exp string subSpec ?varName? puts "$newStmt" regsub –nocase –all "fan" $stmt "Kristy"newStmt puts "$newStmt" • regexp(returns 1 if the regular expression matches the string, else returns 0) puts [regexp –nocase"fan" $stmt] ?switches? regexp string • format puts [format "%s is a %d-year-old" Fan 26] formatString ?argarg ...?

  25. String operations set statement " Fan is a student " set statement [string trim $statement] puts [string length $statement] puts [string length statement] puts [string index $statement 4] puts [string index $statement end] puts [string first"is" $statement] (string last) puts [string first $statement "is"] puts [string range $statement 4 end] puts [string replace $statement 9 end "professor"] puts [string match"*student" $statement] (* ? [])

  26. File Operations set fRead [open source.txt r] set fWrite [open target.txt w] while {![eof $fRead]} { set strLine [gets $fRead] ;#or gets $fReadstrLine regsub –nocase –all "fan" $strLine"kristy" strLine puts $fWrite $strLine } close $fRead close $fWrite ################ source.txt ################ Fan is a CSE student. Fan is also one of Shania’s fans. Kristy and Fan are classmates.

  27. Miscellaneous commands • eval: execute a command dynamically built up in your program set Script { set Number1 17 set Number2 25 set Result [expr $Number1 + $Number2] } eval $Script • exec: execute external programs • clock • trace • info • after

More Related