Tcl/Tk – Discussion

Discuss Tcl-Tk ”; Previous Next Tcl is a general purpose multi-paradigm system programming language. It is a scripting language that aims at providing the ability for applications to communicate with each other. On the other hand, Tk is a cross platform widget toolkit used for building GUI in many languages. This tutorial covers various topics ranging from the basics of the Tcl/Tk to its scope in various applications. Print Page Previous Next Advertisements ”;

Tcl/Tk – Useful Resources

Tcl-Tk – Useful Resources ”; Previous Next The following resources contain additional information on Tcl-Tk. Please use them to get more in-depth knowledge on this topic. Useful Links on Tcl-Tk Official Site – Official Site for Tcl-Tk Details about Tcl-Tk − Wikipedia Reference for Tcl-Tk More Details – Know more details about Tcl-Tk Useful Books on Tcl-Tk To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Tk – Geometry Manager

Tk – Geometry Manager ”; Previous Next The geometry manager is used to manage the geometry of the window and other frames. We can use it to handle the position and size of the window and frames. The layout widgets are used for this purpose. Positioning and sizing The syntax for positioning and sizing window is shown below − wm geometry . wxh+/-x+/-y Here, w refers to width and h refers to height. It is followed by a ”+” or ”-” sign with number next referring to the x position on screen. Similarly the following ”+” or ”-” sign with number refers to the y position on screen A simple example is shown below for the above Statement −. #!/usr/bin/wish wm geometry . 300×200+100+100 When we run the above program, we will get the following output − Grid Geometry The syntax for grid geometry is shown below − grid gridName -column number -row number -columnspan number -rowspan number The column, row, columnspan, or rowspan helps in providing the grid geometry. A simple example is shown below for the above statement − #!/usr/bin/wish frame .myFrame1 -background red -height 100 -width 100 frame .myFrame2 -background blue -height 100 -width 50 grid .myFrame1 -columnspan 10 -rowspan 10 -sticky w grid .myFrame2 -column 10 -row 2 When we run the above program, we will get the following output − Print Page Previous Next Advertisements ”;

Tcl – Error Handling

Tcl – Error Handling ”; Previous Next Error handling in Tcl is provided with the help of error and catch commands. The syntax for each of these commands is shown below. Error syntax error message info code In the above error command syntax, message is the error message, info is set in the global variable errorInfo and code is set in the global variable errorCode. Catch Syntax catch script resultVarName In the above catch command syntax, script is the code to be executed, resultVarName is variable that holds the error or the result. The catch command returns 0 if there is no error, and 1 if there is an error. An example for simple error handling is shown below − Live Demo #!/usr/bin/tclsh proc Div {a b} { if {$b == 0} { error “Error generated by error” “Info String for error” 401 } else { return [expr $a/$b] } } if {[catch {puts “Result = [Div 10 0]”} errmsg]} { puts “ErrorMsg: $errmsg” puts “ErrorCode: $errorCode” puts “ErrorInfo:n$errorInfon” } if {[catch {puts “Result = [Div 10 2]”} errmsg]} { puts “ErrorMsg: $errmsg” puts “ErrorCode: $errorCode” puts “ErrorInfo:n$errorInfon” } When the above code is executed, it produces the following result − ErrorMsg: Error generated by error ErrorCode: 401 ErrorInfo: Info String for error (procedure “Div” line 1) invoked from within “Div 10 0” Result = 5 As you can see in the above example, we can create our own custom error messages. Similarly, it is possible to catch the error generated by Tcl. An example is shown below − Live Demo #!/usr/bin/tclsh catch {set file [open myNonexistingfile.txt]} result puts “ErrorMsg: $result” puts “ErrorCode: $errorCode” puts “ErrorInfo:n$errorInfon” When the above code is executed, it produces the following result − ErrorMsg: couldn”t open “myNonexistingfile.txt”: no such file or directory ErrorCode: POSIX ENOENT {no such file or directory} ErrorInfo: couldn”t open “myNonexistingfile.txt”: no such file or directory while executing “open myNonexistingfile.txt” Print Page Previous Next Advertisements ”;

Tcl – File I/O

Tcl – File I/O ”; Previous Next Tcl supports file handling with the help of the built in commands open, read, puts, gets, and close. A file represents a sequence of bytes, does not matter if it is a text file or binary file. Opening Files Tcl uses the open command to open files in Tcl. The syntax for opening a file is as follows − open fileName accessMode Here, filename is string literal, which you will use to name your file and accessMode can have one of the following values − Sr.No. Mode & Description 1 r Opens an existing text file for reading purpose and the file must exist. This is the default mode used when no accessMode is specified. 2 w Opens a text file for writing, if it does not exist, then a new file is created else existing file is truncated. 3 a Opens a text file for writing in appending mode and file must exist. Here, your program will start appending content in the existing file content. 4 r+ Opens a text file for reading and writing both. File must exist already. 5 w+ Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist. 6 a+ Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning, but writing can only be appended. Closing a File To close a file, use the close command. The syntax for close is as follows − close fileName Any file that has been opened by a program must be closed when the program finishes using that file. In most cases, the files need not be closed explicitly; they are closed automatically when File objects are terminated automatically. Writing a File Puts command is used to write to an open file. puts $filename “text to write” A simple example for writing to a file is shown below. #!/usr/bin/tclsh set fp [open “input.txt” w+] puts $fp “test” close $fp When the above code is compiled and executed, it creates a new file input.txt in the directory that it has been started under (in the program”s working directory). Reading a File Following is the simple command to read from a file − set file_data [read $fp] A complete example of read and write is shown below − Live Demo #!/usr/bin/tclsh set fp [open “input.txt” w+] puts $fp “test” close $fp set fp [open “input.txt” r] set file_data [read $fp] puts $file_data close $fp When the above code is compiled and executed, it reads the file created in previous section and produces the following result − test Here is another example for reading file till end of file line by line − Live Demo #!/usr/bin/tclsh set fp [open “input.txt” w+] puts $fp “testntest” close $fp set fp [open “input.txt” r] while { [gets $fp data] >= 0 } { puts $data } close $fp When the above code is compiled and executed, it reads the file created in previous section and produces the following result − test test Print Page Previous Next Advertisements ”;

Tk – Events

Tk – Events ”; Previous Next Events in its simplest form is handled with the help of commands. A simple example for event handling is event handling with button and is shown below − #!/usr/bin/wish proc myEvent { } { puts “Event triggered” } pack [button .myButton1 -text “Button 1” -command myEvent] When we run the above program, we will get the following output − A simple program to show delay text animation event is shown below − #!/usr/bin/wish proc delay {} { for {set j 0} {$j < 100000} {incr j} {} } label .myLabel -text “Hello…………….” -width 25 pack .myLabel set str “Hello…………….” for {set i [string length $str]} {$i > -2} {set i [expr $i-1]} { .myLabel configure -text [string range $str 0 $i] update delay } When we run the program, we will get the following output in animated way − Event after delay The syntax for event after delay is shown below − after milliseconds number command A simple program to show after delay event is shown below − #!/usr/bin/wish proc addText {} { label .myLabel -text “Hello…………….” -width 25 pack .myLabel } after 1000 addText When we run the program, we will get the following output after one second − You can cancel an event using the after cancel command as shown below − #!/usr/bin/wish proc addText {} { label .myLabel -text “Hello…………….” -width 25 pack .myLabel } after 1000 addText after cancel addText Event Binding The syntax for event binding is as shown below − bind arguments Keyboard Events Example #!/usr/bin/wish bind . {puts “Key Pressed: %K “} When we run the program and press a letter X, we will get the following output − Key Pressed: X Mouse Events Example #!/usr/bin/wish bind . {puts “Button %b Pressed : %x %y “} When we run the program and press the left mouse button, we will get an output similar to the following − Button 1 Pressed : 89 90 Linking Events with Button Example #!/usr/bin/wish proc myEvent { } { puts “Event triggered” } pack [button .myButton1 -text “Button 1” -command myEvent] bind . “.myButton1 invoke” When we run the program and press enter, we will get the following output − Event triggered Print Page Previous Next Advertisements ”;

Tk – Overview

Tk – Overview ”; Previous Next Tk refers to Toolkit and it provides cross platform GUI widgets, which helps you in building a Graphical User Interface. It was developed as an extension to Tcl scripting language by John Ousterhout. Tk remained in development independently from Tcl with version being different to each other, before, it was made in sync with Tcl in v8.0. Features of Tk It is cross platform with support for Linux, Mac OS, Unix, and Microsoft Windows operating systems. It is an open source. It provides high level of extendibility. It is customizable. It is configurable. It provides a large number of widgets. It can be used with other dynamic languages and not just Tcl. GUI looks identical across platforms. Applications Built in Tk Large successful applications have been built in Tcl/Tk. Dashboard Soft User Interface Forms GUI for Relational DB Ad Hoc GUI for Relational DB Software/Hardware System Design Xtask – Task Management Musicology with Tcl and Tk Calender app Tk mail Tk Debugger Print Page Previous Next Advertisements ”;

Tk – Images

Tk – Images ”; Previous Next The image widget is used to create and manipulate images. The syntax for creating image is as follows − image create type name options In the above syntax type is photo or bitmap and name is the image identifier. Options The options available for image create are listed below in the following table − Sr.No. Syntax & Description 1 -file fileName The name of the image file name. 2 -height number Used to set height for widget. 3 -width number Sets the width for widget. 4 -data string Image in base 64 encoded string. A simple example for image widget is shown below − #!/usr/bin/wish image create photo imgobj -file “/Users/rajkumar/Desktop/F Drive/pictur/vb/Forests/ 680049.png” -width 400 -height 400 pack [label .myLabel] .myLabel configure -image imgobj When we run the above program, we will get the following output − The available function for image are listed below in the following table − Sr.No. Syntax & Description 1 image delete imageName Deletes the image from memory and related widgets visually. 2 image height imageName Returns the height for image. 3 image width imageName Returns the width for image. 4 image type imageName Returns the type for image. 5 image names Returns the list of images live in memory. A simple example for using the above image widget commands is shown below − #!/usr/bin/wish image create photo imgobj -file “/Users/rajkumar/images/680049.png” -width 400 -height 400 pack [label .myLabel] .myLabel configure -image imgobj puts [image height imgobj] puts [image width imgobj] puts [image type imgobj] puts [image names] image delete imgobj The image will be deleted visually and from memory once “image delete imgobj” command executes. In console, the output will be like the following − 400 400 photo imgobj ::tk::icons::information ::tk::icons::error ::tk::icons:: warning ::tk::icons::question Print Page Previous Next Advertisements ”;

Tcl – Variables

Tcl – Variables ”; Previous Next In Tcl, there is no concept of variable declaration. Once, a new variable name is encountered, Tcl will define a new variable. Variable Naming The name of variables can contain any characters and length. You can even have white spaces by enclosing the variable in curly braces, but it is not preferred. The set command is used for assigning value to a variable. The syntax for set command is, set variableName value A few examples of variables are shown below − Live Demo #!/usr/bin/tclsh set variableA 10 set {variable B} test puts $variableA puts ${variable B} When the above code is executed, it produces the following result − 10 test As you can see in the above program, the $variableName is used to get the value of the variable. Dynamic Typing Tcl is a dynamically typed language. The value of the variable can be dynamically converted to the required type when required. For example, a number 5 that is stored as string will be converted to number when doing an arithmetic operation. It is shown below − Live Demo #!/usr/bin/tclsh set variableA “10” puts $variableA set sum [expr $variableA +20]; puts $sum When the above code is executed, it produces the following result − 10 30 Mathematical Expressions 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, we should add at least a single decimal digit. A simple example explains the above. Live Demo #!/usr/bin/tclsh set variableA “10” set result [expr $variableA / 9]; puts $result set result [expr $variableA / 9.0]; puts $result set variableA “10.0” set result [expr $variableA / 9]; puts $result When the above code is executed, it produces the following result − 1 1.1111111111111112 1.1111111111111112 In the above example, you can see three cases. In the first case, the dividend and the divisor are whole numbers and we get a whole number as result. In the second case, the divisor alone is a decimal number and in the third case, the dividend is a decimal number. In both second and third cases, we get a decimal number as result. In the above code, you can change the precision by using tcl_precision special variable. It is shown below − Live Demo #!/usr/bin/tclsh set variableA “10” set tcl_precision 5 set result [expr $variableA / 9.0]; puts $result When the above code is executed, it produces the following result − 1.1111 Print Page Previous Next Advertisements ”;

Tcl – Regular Expressions

Tcl – Regular Expressions ”; Previous Next The “regexp” command is used to match a regular expression in Tcl. A regular expression is a sequence of characters that contains a search pattern. It consists of multiple rules and the following table explains these rules and corresponding use. Sr.No. Rule & Description 1 x Exact match. 2 [a-z] Any lowercase letter from a-z. 3 . Any character. 4 ^ Beginning string should match. 5 $ Ending string should match. 6 ^ Backlash sequence to match special character ^.Similarly you can use for other characters. 7 () Add the above sequences inside parenthesis to make a regular expression. 8 x* Should match 0 or more occurrences of the preceding x. 9 x&plus; Should match 1 or more occurrences of the preceding x. 10 [a-z]? Should match 0 or 1 occurrence of the preceding x. 11 {digit} Matches exactly digit occurrences of previous regex expression. Digit that contains 0-9. 12 {digit,} Matches 3 or more digit occurrences of previous regex expression. Digit that contains 0-9. 13 {digit1,digit2} Occurrences matches the range between digit1 and digit2 occurrences of previous regex expression. Syntax The syntax for regex is given below − regexp optionalSwitches patterns searchString fullMatch subMatch1 … subMatchn Here, regex is the command. We will see about optional switches later. Patterns are the rules as mentioned earlier. Search string is the actual string on which the regex is performed. Full match is any variable to hold the result of matched regex result. Submatch1 to SubMatchn are optional subMatch variable that holds the result of sub match patterns. Let”s look at some simple examples before diving into complex ones. A simple example for a string with any alphabets. When any other character is encountered the regex, search will be stopped and returned. Live Demo #!/usr/bin/tclsh regexp {([A-Za-z]*)} “Tcl Tutorial” a b puts “Full Match: $a” puts “Sub Match1: $b” When the above code is executed, it produces the following result − Full Match: Tcl Sub Match1: Tcl Multiple Patterns The following example shows how to search for multiple patterns. This is example pattern for any alphabets followed by any character followed by any alphabets. Live Demo #!/usr/bin/tclsh regexp {([A-Za-z]*).([A-Za-z]*)} “Tcl Tutorial” a b c puts “Full Match: $a” puts “Sub Match1: $b” puts “Sub Match2: $c” When the above code is executed, it produces the following result − Full Match: Tcl Tutorial Sub Match1: Tcl Sub Match2: Tutorial A modified version of the above code to show that a sub pattern can contain multiple patterns is shown below − Live Demo #!/usr/bin/tclsh regexp {([A-Za-z]*.([A-Za-z]*))} “Tcl Tutorial” a b c puts “Full Match: $a” puts “Sub Match1: $b” puts “Sub Match2: $c” When the above code is executed, it produces the following result − Full Match: Tcl Tutorial Sub Match1: Tcl Tutorial Sub Match2: Tutorial Switches for Regex Command The list of switches available in Tcl are, nocase − Used to ignore case. indices − Store location of matched sub patterns instead of matched characters. line − New line sensitive matching. Ignores the characters after newline. start index − Sets the offset of start of search pattern. Marks the end of switches In the above examples, I have deliberately used [A-Z, a-z] for all alphabets, you can easily use -nocase instead of as shown below − Live Demo #!/usr/bin/tclsh regexp -nocase {([A-Z]*.([A-Z]*))} “Tcl Tutorial” a b c puts “Full Match: $a” puts “Sub Match1: $b” puts “Sub Match2: $c” When the above code is executed, it produces the following result − Full Match: Tcl Tutorial Sub Match1: Tcl Tutorial Sub Match2: Tutorial Another example using switches is shown below − Live Demo #!/usr/bin/tclsh regexp -nocase -line — {([A-Z]*.([A-Z]*))} “Tcl nTutorial” a b puts “Full Match: $a” puts “Sub Match1: $b” regexp -nocase -start 4 -line — {([A-Z]*.([A-Z]*))} “Tcl nTutorial” a b puts “Full Match: $a” puts “Sub Match1: $b” When the above code is executed, it produces the following result − Full Match: Tcl Sub Match1: Tcl Full Match: Tutorial Sub Match1: Tutorial Print Page Previous Next Advertisements ”;