Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming Using Tcl/Tk Week 4 Seree Chinodom

Similar presentations


Presentation on theme: "Programming Using Tcl/Tk Week 4 Seree Chinodom"— Presentation transcript:

1 Programming Using Tcl/Tk Week 4 Seree Chinodom seree@buu.ac.th http://lecture.compsci.buu.ac.th/TclTk

2 First Things First ฉ Homework #1: Only 4 out of 10? –Don't have software? –Not for credit? –Need more help? ฉ Homework #2: Hand them in, if you've got 'em ฉ The story about the readers…

3 TkCal Example ############################## # initialize global variables set months {January February March April May June July \ August September October November December} # figure out the current month and year # date returns a string like Sun Sep 22 22:26:10 PDT 1996 set d [exec date] set month [lindex $d 1] set year [lindex $d 5] # expand the abbreviation that date gave us foreach m $months { if {[string match ${month}* $m] == 1} { set month $m break }

4 TkCal (continued) ############################## # Menu action proc doMenu {m} { global month set month $m.f.mb configure -text $m } ############################## # run cal and collect output proc showCalendar {} { global month year months set m [expr [lsearch $months $month] + 1] if {[catch {set cal [exec cal $m $year]} err] == 1} { set cal $err }.t delete 1.0 end.t insert 1.0 $cal }

5 TkCal (continued) ############################## # set up widgets frame.f pack.f -side top -fill x -expand 1 menubutton.f.mb -text $month -menu.f.mb.m -width 12 pack.f.mb -side left menu.f.mb.m foreach m $months {.f.mb.m add command -label $m -command "doMenu $m" }

6 TkCal (continued) entry.f.e -textvariable year -width 5 pack.f.e -side left button.b -text "See Calendar" -command showCalendar pack.b -side top -pady 3 -fill x text.t -width 21 -height 8 pack.t -side bottom -fill x ############################## # initial display showCalendar

7 What We'll Do Today ฉ A Few Miscellaneous Details ฉ Using the Text and Canvas Widgets ฉ More Advanced Examples ฉ Writing 'Tclets' for the World Wide Web

8 Tcl/Tk Addendum ฉ cget widget command to query configuration options.w cget -foreground => black Much easier than.w configure -foreground! ฉ env array containing environment variables cd $env(HOME) exec $env(EDITOR)

9 The Text Widget ฉ Multiline text area widget with 1001 features: –Editing ท (Emacs key bindings: ^A, ^E, ^K, ^Y, ^F, ^B, etc) –Scrolling (manual and from code; X and Y axes) –Flexible text formatting: multiple fonts and colors –Text tags: content-sensitve formats and behaviors –Selection manipulation ฉ Arranges text and embedded widget in lines; lines can wrap but not flow

10 The Text Widget ฉ Special widget commands: setgetdeleteselectmark tagsearchseewindowyview xviewbind ฉ Special widget configuration options -state-height-width -spacing1-spacing2-spacing3 -state-tabs -insertbackground-selectbackground

11 The Text Widget ฉ Referring to text within a text widget –index: line.char (line starts at 1, char starts at 0) –position: @x,y (character closest to pixel x,y) –mark: Basically a name for an index..t mark set myplace 6.23 –tag: Names for sets of ranges of text.t tag add mywords 6.23 6.30.t tag add mywords 7.41 7.46

12 The Text Widget ฉ Tagged text can be configured.t tag configure mywords -foreground red ฉ Tagged text can have bindings!.t tag bind mywords { exec TkEdit mywordlist.txt }

13 The Text Widget ฉ Text widgets can serve as geometry managers for other widgets: image create photo -file bart.gif label.t.l -image image1.t window create 1.5.t.l

14 A Syntax-Coloring Mini-Editor ฉ "TkEmacs" does customizable syntax coloring using regular expressions, like Emacs' hilit-19 package ฉ One text widget ฉ One scroll widget ฉ Can read and save files ฉ About 100 lines of well-commented code

15 TkEmacs (continued) proc forAllMatches {w pattern script} { # determine number of lines in widget scan [$w index end] %d numLines ;# returns e.g. 9.32 for {set i 1} {$i < $numLines} {incr i} { $w mark set last $i.0 while {[regexp -indices $pattern \ [$w get last "last lineend"] context indices]} { $w mark set first "last + [lindex $indices 0] chars" $w mark set last "last + 1 chars + \ [lindex $indices 1] chars" uplevel $script } forAllMatches Routine

16 TkEmacs (continued) proc doColor {w} { global syntax_patterns global syntax_colors foreach name [array names syntax_patterns] { $w tag delete $name forAllMatches $w $syntax_patterns($name) \ "$w tag add $name first last".t tag configure $name \ -foreground $syntax_colors($name) } doColor Routine

17 TkEmacs (continued) proc loadFile {w file} { $w delete 1.0 end set f [open $file] while {![eof $f]} { \$w insert end [read $f 1000] } close $f } proc writeFile {w file} { set f [open $file "w"] puts $f [$w get 1.0 end] close $f } File Routines

18 TkEmacs (continued) set syntax_patterns(types) \ {[^A-Za-z0-9"](char|short|int|long|unsigned|signed|float|double)} set syntax_colors(types) yellow set syntax_patterns(directives) \ {((#include|#ifdef|#ifndef|#if|#elseif|#else|#pragma|#endif).*$)} set syntax_colors(directives) purple set syntax_patterns(newline_types) \ {^(char|short|int|long|unsigned|signed|float|double)} set syntax_colors(newline_types) yellow set syntax_patterns(keywords) \ {[^"A-Za-z0-9]+(if|then|else|for|goto|while|struct)([^A-Za-z0- 9"]|$)} set syntax_colors(keywords) red set syntax_patterns(comment1) {(/\*.*\*/)} set syntax_colors(comment1) pink set syntax_patterns(comment2) {(//.*$)} set syntax_colors(comment2) pink set syntax_patterns(strings) {("[^"]+")} set syntax_colors(strings) orange

19 TkEmacs (continued) # Set up the widgets text.t \ -yscrollcommand ".s set" \ -insertbackground white \ -width 50 -height 18 pack.t -side left -fill x \ -expand 1.t configure -tabs {32 64 96}.t configure -background black.t configure -foreground white scrollbar.s -command \ ".t yview" pack.s -side right -fill y # Key bindings bind.t {doColor.t} bind.t \ {writeFile.t $FILENAME} bind.t {exit} # Run a little demo set FILENAME [lindex $argv 0] loadFile.t $FILENAME wm title. "TkEmacs $FILENAME" doColor.t

20 The Canvas Widget ฉ Does for drawing primitives what text does for words ฉ Special widget commands: addtagbindcreate deletedtagfind focusgettagsitemconfiguremove postscript ฉ Special widget configuration options -closeenough-scrollregion -xscrollincrement -yscrollincrement

21 The Canvas Widget ฉ Canvases can be "drawn on".c create oval 3 3 200 200 \ -fill yellow -outline black.c create oval 50 50 60 70 \ -fill black -outline black.c create oval 140 50 150 70 -fill black -outline black.c create arc 30 60 170 170 -outline black \ -extent -190 -style arc -width 4 -start 5.c create arc 20 90 40 110 -outline black \ -extent -100 -style arc -width 4 -start 320.c create arc 160 90 180 110 -outline black \ -extent -100 -style arc -width 4 -start 320

22 The Canvas Widget ฉ Each drawing primitive or embedded window is an 'item' with a numeric index.c create oval 3 3 200 200 \ -fill yellow -outline black => 1 ฉ Items can be tagged, as in text widget. c itemconfigure 2 -tag eyes. c itemconfigure 3 -tag eyes

23 The Canvas Widget ฉ Items can be searched for in many ways.c find closest 50 60 ;# canvas coords => 2 ;# left eye ฉ Items and tags can have bindings.c bind eyes {Wink %W %x %y}.c bind eyes {Unwink %W %x %y}

24 Furniture Arranger ฉ A simple app to help you decide how to arrange your furniture ฉ Uses drawing primitives to represent pieces of furniture ฉ Uses multiple tags per item ฉ Implements behaviors based on tags

25 Furniture Arranger proc setupCanvas {} { catch {destroy.c} canvas.c pack.c # create chairs foreach i { 100 130 160 190 } {.c create rect $i 100 [expr $i+20] 120 \ -fill red -tags {chair furniture} } # setup Chair behavior.c bind chair {.c itemconfigure current -fill blue}.c bind chair {.c itemconfigure current -fill red}... setupCanvas, part 1

26 Furniture Arranger... #create Table.c create oval 20 20 100 150 -fill pink \ -tags {table rotatable furniture} # setup Table behavior.c bind table {.c itemconfigure current -fill skyblue}.c bind table {.c itemconfigure current -fill pink} #create Couch.c create rect 20 200 200 250 -fill orange \ -tags {couch rotatable furniture} # setup Couch behavior.c bind couch {.c itemconfigure current -fill green}.c bind couch {.c itemconfigure current -fill orange}... setupCanvas, part 2

27 Furniture Arranger... # setup 'rotatable' behavior.c bind rotatable rotate # setup Furniture behavior.c bind furniture { set curX %x set curY %y }.c bind furniture {.c move current [expr (%x-$curX)] [expr (%y-$curY)] set curX %x; set curY %y } setupCanvas, part 3

28 Furniture Arranger proc rotate {} { set r [.c find withtag current] set coords [.c coords $r] set x2 [expr ([lindex $coords 2] - [lindex $coords 0]) / 2] set y2 [expr ([lindex $coords 3] - [lindex $coords 1]) / 2] set xc [expr [lindex $coords 0] + $x2] set yc [expr [lindex $coords 1] + $y2].c coords $r [expr $xc - $y2] \ [expr $yc - $x2] \ [expr $xc + $y2] \ [expr $yc + $x2] } setupCanvas bind. setupCanvas wm title. "Furniture Arranger" rotate and mainline

29 Tclets ฉ Sun has released a Netscape 'plug-in' for Tcl/Tk ฉ Your Tcl/Tk programs can run as 'Tclets' inside Netscape if you remember a few simple things –Filesystem access is severely restricted –Exec'ing is prohibited –Network access is prohibited –Grabbing display prohibited –direct window manager interaction prohibited –No menu widgets ฉ What can you do with this? –Tools like a calculator –Graphical demonstrations –Games

30 Tclets ฉ Only users who ahev installed the plug-in can use your Tclets ฉ Tclet filesystem access is limited to: –Using source and load in script directories only –Using open (read only) in script directories –Using the new command maketmp to create read- write temporary files –You can't get a file listing! –No stdout, stdin ฉ Some commands have extensions to help –image data can come from a MIME encoded string

31 Making 'Furniture Mover' a Tclet ฉ The Furniture Mover app makes a perfect Tclet. Anyone in the world could rearrange your furniture! ฉ One change to source: if {[info exists embed_args] == 0} { wm title. "Furniture Arranger" } ฉ embed_args is an array containing parameters from HTML - you can use them as command line args for your Tclet

32 Making 'Furniture Mover' a Tclet ฉ Next, create a page of HTML: Furniture Moving Tclet Friedman-Hill Home Furniture Planning Kit This Tclet lets you rearrange the furniture in an imaginary room from the Friedman-Hill mansion. See what you can do to improve the work of a decorating genius!

33 Deploying Tclets ฉ Place furniture.tcl and furniture.html in the same directory in your area or on a web server ฉ Visiting the html file with Netscape will show the Tclet (if the plug-in is installed). ฉ Tip: include a link to the Tcl Plug-in home page and a brief explanation on each of your Tclet-enhanced pages

34 For Next Week... ฉ Review today's material in Ousterhout, Chapter 19 ฉ Read Ousterhout Chapter 28-30 to prepare for next week's lecture on extending Tcl with C ฉ Also next week: a look at some Tcl extensions ฉ Projects due next week –Bring screenshots if you can (as vugraphs if possible) –Please be prepared to talk for five minutes or so


Download ppt "Programming Using Tcl/Tk Week 4 Seree Chinodom"

Similar presentations


Ads by Google