Chinese in Canada

Knowledge Management and Collaboration Platform for chinese who are living in Canada.
Welcome to Chinese in Canada Sign in | Join | Help
in
Home Blogs Forums Photos Files Roller

Tcl Programming/Tk examples

Last post 10-09-2009, 1:44 PM by Johnz. 3 replies.
Sort Posts: Previous Next
  •  06-18-2009, 10:17 AM 7931

    Tcl Programming/Tk examples

    The following examples originally appeared in the Tcler's Wiki http://wiki.tcl.tk . They are all in the public domain - no rights reserved.

    Contents

    [hide]
    //

    [edit] A funny cookbook

    This funny little program produces random cooking recipes. Small as it is, it can produce 900 different recipes, though they might not be to everybody's taste... The basic idea is to pick an arbitrary element from a list, which is easily done in Tcl with the following:

    proc ? L {lindex $L [expr {int(rand()*[llength $L])}]}

    This is used several times in:

    proc recipe {} {
    set a {
    {3 eggs} {an apple} {a pound of garlic}
    {a pumpkin} {20 marshmallows}
    }
    set b {
    {Cut in small pieces} {Dissolve in lemonade}
    {Bury in the ground for 3 months}
    {Bake at 300 degrees} {Cook until tender}
    }
    set c {parsley snow nutmeg curry raisins cinnamon}
    set d {
    ice-cream {chocolate cake} spinach {fried potatoes} rice {soy sprouts}
    }
    return " Take [? $a].
    [? $b].
    Top with [? $c].
    Serve with [? $d]."
    }

    And as modern programs always need a GUI, here is a minimal one that appears when you source this file at top level, and shows a new recipe every time you click on it:

    if {[file tail [info script]]==[file tail $argv0]} {
    package require Tk
    pack [text .t -width 40 -height 5]
    bind .t <1> {showRecipe %W; break}
    proc showRecipe w {
    $w delete 1.0 end
    $w insert end [recipe]
    }
    showRecipe .t
    }

    Enjoy!

    [edit] A little A/D clock

    This is a clock that shows time either analog or digital - just click on it to toggle.

    #!/usr/bin/env tclsh
    package require Tk
    proc every {ms body} {eval $body; after $ms [info level 0]}
    proc drawhands w {
    $w delete hands
    set secSinceMidnight [expr {[clock sec]-[clock scan 00:00:00]}]
    foreach divisor {60 3600 43200} length {45 40 30} width {1 3 7} {
    set angle [expr {$secSinceMidnight * 6.283185 / $divisor}]
    set x [expr {50 + $length * sin($angle)}]
    set y [expr {50 - $length * cos($angle)}]
    $w create line 50 50 $x $y -width $width -tags hands
    }
    }
    proc toggle {w1 w2} {
    if [winfo ismapped $w2] {
    foreach {w2 w1} [list $w1 $w2] break ;# swap
    }
    pack forget $w1
    pack $w2
    }
    #-- Creating the analog clock:
    canvas .analog -width 100 -height 100 -bg white
    every 1000 {drawhands .analog}
    pack .analog
    #-- Creating the digital clock:
    label .digital -textvar ::time -font {Courier 24}
    every 1000 {set ::time [clock format [clock sec] -format %H:%M:%S]}
    bind . <1> {toggle .analog .digital}

    [edit] A little pie chart

    image:TkPiechart.jpg

    Arc elements of a canvas are by default rendered as pie slices (part of the circumference of a circle, connected by radius lines to the center. Hence it s rather easy to produce a pie chart. The following code is a bit more complex, as it also determines positions for the labels of the pies:

    proc piechart {w x y width height data} {
    set coords [list $x $y [expr {$x+$width}] [expr {$y+$height}]]
    set xm [expr {$x+$width/2.}]
    set ym [expr {$y+$height/2.}]
    set rad [expr {$width/2.+20}]
    set sum 0
    foreach item $data {set sum [expr {$sum + [lindex $item 1]}]}
    set start 270
    foreach item $data {
    foreach {name n color} $item break
    set extent [expr {$n*360./$sum}]
    $w create arc $coords -start $start -extent $extent -fill $color
    set angle [expr {($start-90+$extent/2)/180.*acos(-1)}]
    set tx [expr $xm-$rad*sin($angle)]
    set ty [expr $ym-$rad*cos($angle)]
    $w create text $tx $ty -text $name:$n -tag txt
    set start [expr $start+$extent]
    }
    $w raise txt
    }

    Testing:

    pack [canvas .c -bg white]
    piechart .c 50 50 150 150 {
    {SPD 199 red}
    {CDU 178 gray}
    {CSU 23 blue}
    {FDP 60 yellow}
    {Grüne 58 green}
    {Linke 55 purple}
    }

    [edit] A little 3D bar chart

    image:3DBarchart.jpg

    The following script displays a bar chart on a canvas, with pseudo-3-dimensional bars - a rectangle in front as specified, embellished with two polygons - one for the top, one for the side:}

    proc 3drect {w args} {
    if [string is int -strict [lindex $args 1]] {
    set coords [lrange $args 0 3]
    } else {
    set coords [lindex $args 0]
    }
    foreach {x0 y0 x1 y1} $coords break
    set d [expr {($x1-$x0)/3}]
    set x2 [expr {$x0+$d+1}]
    set x3 [expr {$x1+$d}]
    set y2 [expr {$y0-$d+1}]
    set y3 [expr {$y1-$d-1}]
    set id [eval [list $w create rect] $args]
    set fill [$w itemcget $id -fill]
    set tag [$w gettags $id]
    $w create poly $x0 $y0 $x2 $y2 $x3 $y2 $x1 $y0 \
    -fill [dim $fill 0.8] -outline black
    $w create poly $x1 $y1 $x3 $y3 $x3 $y2 $x1 $y0 \
    -fill [dim $fill 0.6] -outline black -tag $tag
    }

    For a more plastic look, the fill color of the polygons is reduced in brightness ("dimmed"):

    proc dim {color factor} {
    foreach i {r g b} n [winfo rgb . $color] d [winfo rgb . white] {
    set $i [expr int(255.*$n/$d*$factor)]
    }
    format #%02x%02x%02x $r $g $b
    }

    Draw a simple scale for the y axis, and return the scaling factor:

    proc yscale {w x0 y0 y1 min max} {
    set dy [expr {$y1-$y0}]
    regexp {([1-9]+)} $max -> prefix
    set stepy [expr {1.*$dy/$prefix}]
    set step [expr {$max/$prefix}]
    set y $y0
    set label $max
    while {$label>=$min} {
    $w create text $x0 $y -text $label -anchor w
    set y [expr {$y+$stepy}]
    set label [expr {$label-$step}]
    }
    expr {$dy/double($max)}
    }

    An interesting sub-challenge was to round numbers very roughly, to 1 or maximally 2 significant digits - by default rounding up, add "-" to round down:

    proc roughly {n {sgn +}} {
    regexp {(.+)e([+-])0*(.+)} [format %e $n] -> mant sign exp
    set exp [expr $sign$exp]
    if {abs($mant)<1.5} {
    set mant [expr $mant*10]
    incr exp -1
    }
    set t [expr round($mant $sgn 0.49)*pow(10,$exp)]
    expr {$exp>=0? int($t): $t}
    }

    So here is my little bar chart generator. Given a canvas pathname, a bounding rectangle, and the data to display (a list of {name value color} triples), it figures out the geometry. A gray "ground plane" is drawn first. Note how negative values are tagged with "d"(eficit), so they look like they "drop through the plane".

    proc bars {w x0 y0 x1 y1 data} {
    set vals 0
    foreach bar $data {
    lappend vals [lindex $bar 1]
    }
    set top [roughly [max $vals]]
    set bot [roughly [min $vals] -]
    set f [yscale $w $x0 $y0 $y1 $bot $top]
    set x [expr $x0+30]
    set dx [expr ($x1-$x0-$x)/[llength $data]]
    set y3 [expr $y1-20]
    set y4 [expr $y1+10]
    $w create poly $x0 $y4 [expr $x0+30] $y3 $x1 $y3 [expr $x1-20] $y4 -fill gray65
    set dxw [expr $dx*6/10]
    foreach bar $data {
    foreach {txt val col} $bar break
    set y [expr {round($y1-($val*$f))}]
    set y1a $y1
    if {$y>$y1a} {swap y y1a}
    set tag [expr {$val<0? "d": ""}]
    3drect $w $x $y [expr $x+$dxw] $y1a -fill $col -tag $tag
    $w create text [expr {$x+12}] [expr {$y-12}] -text $val
    $w create text [expr {$x+12}] [expr {$y1a+2}] -text $txt -anchor n
    incr x $dx
    }
    $w lower d
    }

    Generally useful helper functions:

    proc max list {
    set res [lindex $list 0]
    foreach e [lrange $list 1 end] {
    if {$e>$res} {set res $e}
    }
    set res
    }
    proc min list {
    set res [lindex $list 0]
    foreach e [lrange $list 1 end] {
    if {$e<$res} {set res $e}
    }
    set res
    }
    proc swap {_a _b} {
    upvar 1 $_a a $_b b
    foreach {a b} [list $b $a] break
    }

    Testing the whole thing (see screenshot):

    pack [canvas .c -width 240 -height 280]
    bars .c 10 20 240 230 {
    {red 765 red}
    {green 234 green}
    {blue 345 blue}
    {yel-\nlow 321 yellow}
    {ma-\ngenta 567 magenta}
    {cyan -123 cyan}
    {white 400 white}
    }
    .c create text 120 10 -anchor nw -font {Helvetica 18} -text "Bar Chart\nDemo"

    [edit] A little calculator

    Image:Calculator.jpg

    Here is a small calculator in Tcl/Tk. In addition to the buttons on screen, you can use any of expr's other functionalities via keyboard input.

    package require Tk
    wm title . Calculator
    grid [entry .e -textvar e -just right] -columnspan 5
    bind .e <Return> =
    set n 0
    foreach row {
    {7 8 9 + -}
    {4 5 6 * /}
    {1 2 3 ( )}
    {C 0 . = }
    } {
    foreach key $row {
    switch -- $key {
    = {set cmd =}
    C {set cmd {set clear 1; set e ""}}
    default {set cmd "hit $key"}
    }
    lappend keys [button .[incr n] -text $key -command $cmd]
    }
    eval grid $keys -sticky we ;#-padx 1 -pady 1
    set keys [list]
    }
    grid .$n -columnspan 2 ;# make last key (=) double wide
    proc = {} {
    regsub { =.+} $::e "" ::e ;# maybe clear previous result
    if [catch {set ::res [expr [string map {/ *1.0/} $::e]]}] {
    .e config -fg red
    }
    append ::e = $::res
    .e xview end
    set ::clear 1
    }
    proc hit {key} {
    if $::clear {
    set ::e ""
    if ![regexp {[0-9().]} $key] {set ::e $::res}
    .e config -fg black
    .e icursor end
    set ::clear 0
    }
    .e insert end $key
    }
    set clear 0
    focus .e ;# allow keyboard input
    wm resizable . 0 0

    And, as Cameron Laird noted, this thingy is even programmable: enter for example

    [proc fac x {expr {$x<2? 1: $x*[fac [incr x -1]]}}]

    into the entry, disregard warnings; now you can do

    [fac 10]

    and receive [fac 10] = 3628800.0 as result...

    [edit] A little slide rule

    The slide rule was an analog, mechanical device for approximate engineering computing, made obsolete by the pocket calculator since about the 1970-80s. The basic principle is that multiplication is done by adding logarithms, hence most of the scales are logarithmic, with uneven increments.

    Image:Sliderule_Tk.jpg

    This fun project recreates a slide rule (roughly an Aristo-Rietz Nr. 89 with 7 scales - high-notch ones had up to 24) with a white "body" and a beige "slide" which you can move left or right with mouse button 1 clicked, or in pixel increment with the <Shift-Left>/<Shift-Right> cursor keys. Finally, the blue line represents the "mark" (how is that correctly called? "runner"? "slider"?) which you can move with the mouse over the whole thing to read a value. Fine movements with <Left>/<Right>.

    Due to rounding errors (integer pixels), this plaything is even less precise than a physical slide rule was, but maybe you still enjoy the memories... The screenshot shows how I found out that 3 times 7 is approx. 21... (check the A and B scales).

    proc ui {} {
    set width 620
    pack [canvas .c -width $width -height 170 -bg white]
    pack [label .l -textvariable info -fg blue] -fill x
    .c create rect 0 50 $width 120 -fill grey90
    .c create rect 0 50 $width 120 -fill beige -outline beige \
    -tag {slide slidebase}
    .c create line 0 0 0 120 -tag mark -fill blue
    drawScale .c K x3 10 5 5 log10 1 1000 186.6666667
    drawScale .c A x2 10 50 -5 log10 1 100 280
    drawScale .c B x2 10 50 5 log10 1 100 280 slide
    drawScale .c CI 1/x 10 90 -5 -log10 1 10 560 slide
    drawScale .c C x 10 120 -5 log10 1 10 560 slide
    drawScale .c D x 10 120 5 log10 1 10 560
    drawScale .c L "lg x" 10 160 -5 by100 0 10 5600
    bind .c <Motion> {.c coords mark %x 0 %x 170; set info [values .c]}
    bind .c <1> {set x %x}
    bind .c <B1-Motion> {%W move slide [expr {%x-$x}] 0; set x %x}
    bind . <Shift-Left> {.c move slide -1 0; set info [values .c]}
    bind . <Shift-Right> {.c move slide 1 0; set info [values .c]}
    bind . <Left> {.c move mark -1 0; set info [values .c]}
    bind . <Right> {.c move mark 1 0; set info [values .c]}
    }
    proc drawScale {w name label x y dy f from to fac {tag {}}} {
    set color [expr {[string match -* $f]? "red": "black"}]
    $w create text $x [expr $y+2*$dy] -text $name -tag $tag -fill $color
    $w create text 600 [expr $y+2*$dy] -text $label -tag $tag -fill $color
    set x [expr {[string match -* $f]? 580: $x+10}]
    set mod 5
    set lastlabel ""
    set lastx 0
    for {set i [expr {$from*10}]} {$i<=$to*10} {incr i} {
    if {$i>100} {
    if {$i%10} continue ;# coarser increments
    set mod 50
    }
    if {$i>1000} {
    if {$i%100} continue ;# coarser increments
    set mod 500
    }
    set x0 [expr $x+[$f [expr {$i/10.}]]*$fac]
    set y1 [expr {$i%(2*$mod)==0? $y+2.*$dy: $i%$mod==0? $y+1.7*$dy: $y+$dy}]
    set firstdigit [string index $i 0]
    if {$y1==$y+$dy && abs($x0-$lastx)<2} continue
    set lastx $x0
    if {$i%($mod*2)==0 && $firstdigit != $lastlabel} {
    $w create text $x0 [expr $y+3*$dy] -text $firstdigit \
    -tag $tag -font {Helvetica 7} -fill $color
    set lastlabel $firstdigit
    }
    $w create line $x0 $y $x0 $y1 -tag $tag -fill $color
    }
    }
    proc values w {
    set x0 [lindex [$w coords slidebase] 0]
    set x1 [lindex [$w coords mark] 0]
    set lgx [expr {($x1-20)/560.}]
    set x [expr {pow(10,$lgx)}]
    set lgxs [expr {($x1-$x0-20)/560.}]
    set xs [expr {pow(10,$lgxs)}]
    set res K:[format %.2f [expr {pow($x,3)}]]
    append res " A:[format %.2f [expr {pow($x,2)}]]"
    append res " B:[format %.2f [expr {pow($xs,2)}]]"
    append res " CI:[format %.2f [expr {pow(10,-$lgxs)*10}]]"
    append res " C:[format %.2f $xs]"
    append res " D:[format %.2f $x]"
    append res " L:[format %.2f $lgx]"
    }
    proc pow10 x {expr {pow(10,$x)}}
    proc log10 x {expr {log10($x)}}
    proc -log10 x {expr {-log10($x)}}
    proc by100 x {expr {$x/100.}}
    #--------------------------------
    ui
    bind . <Escape> {exec wish $argv0 &; exit}

    [edit] A minimal doodler

    Here is a tiny but complete script that allows doodling (drawing with the mouse) on a canvas widget:

    proc doodle {w {color black}} {
    bind $w <1> [list doodle'start %W %x %y $color]
    bind $w <B1-Motion> {doodle'move %W %x %y}
    }
    proc doodle'start {w x y color} {
    set ::_id [$w create line $x $y $x $y -fill $color]
    }
    proc doodle'move {w x y} {
    $w coords $::_id [concat [$w coords $::_id] $x $y]
    }
    pack [canvas .c -bg white] -fill both -expand 1
    doodle .c
    bind .c <Double-3> {%W delete all}

    Image:Doodler.jpg

    And here it comes again, but this time with explanations:

    The "Application Program Interface" (API) for this, if you want such ceremonial language, is the doodle command, where you specify which canvas widget should be enabled to doodle, and in which color (defaults to black):}

    proc doodle {w {color black}} {
    bind $w <1> [list doodle'start %W %x %y $color]
    bind $w <B1-Motion> {doodle'move %W %x %y}
    }

    It registers two bindings for the canvas, one (<1>) when the left mouse-button is clicked, and the other when the mouse is moved with button 1 (left) down. Both bindings just call one internal function each.

    On left-click, a line item is created on the canvas in the specified fill color, but with no extent yet, as start and end points coincide. The item ID (a number assigned by the canvas) is kept in a global variable, as it will have to persist long after this procedure has returned:

    proc doodle'start {w x y color} {
    set ::_id [$w create line $x $y $x $y -fill $color]
    }

    The left-motion procedure obtains the coordinates (alternating x and y) of the globally known doodling line object, appends the current coordinates to it, and makes this the new cooordinates - in other words, extends the line to the current mouse position:

    proc doodle'move {w x y} {
    $w coords $::_id [concat [$w coords $::_id] $x $y]
    }

    That's all we need to implement doodling - now let's create a canvas to test it, and pack it so it can be drawn as big as you wish:

    pack [canvas .c -bg white] -fill both -expand 1

    And this line turns on the doodle functionality created above (defaulting to black):

    doodle       .c

    Add a binding for double-right-click/double-button-3, to clear the canvas (added by MG, Apr 29 04)

    bind .c <Double-3> {%W delete all}

    [edit] A tiny drawing program

    Here is a tiny drawing program on a canvas. Radio buttons on top allow choice of draw mode and fill color. In "Move" mode, you can of course move items around. Right-click on an item to delete it.

    Image:Tinydraw.jpg

    A radio is an obvious "megawidget" to hold a row of radiobuttons. This simple one allows text or color mode: }

    proc radio {w var values {col 0}} {
    frame $w
    set type [expr {$col? "-background" : "-text"}]
    foreach value $values {
    radiobutton $w.v$value $type $value -variable $var -value $value \
    -indicatoron 0
    if $col {$w.v$value config -selectcolor $value -borderwidth 3}
    }
    eval pack [winfo children $w] -side left
    set ::$var [lindex $values 0]
    set w
    }

    Depending on draw mode, the mouse events "Down" and "Motion" have different handlers, which are dispatched by names that look like array elements. So for a mode X, we need a pair of procs, down(X) and move(X). Values used between calls are kept in global variables.

    First, the handlers for free-hand line drawing:

    proc down(Draw) {w x y} {
    set ::ID [$w create line $x $y $x $y -fill $::Fill]
    }
    proc move(Draw) {w x y} {
    $w coords $::ID [concat [$w coords $::ID] $x $y]
    }
    #-- Movement of an item
    proc down(Move) {w x y} {
    set ::ID [$w find withtag current]
    set ::X $x; set ::Y $y
    }
    proc move(Move) {w x y} {
    $w move $::ID [expr {$x-$::X}] [expr {$y-$::Y}]
    set ::X $x; set ::Y $y
    }
    #-- Clone an existing item
    proc serializeCanvasItem {c item} {
    set data [concat [$c type $item] [$c coords $item]]
    foreach opt [$c itemconfigure $item] {
    # Include any configuration that deviates from the default
    if {[lindex $opt end] != [lindex $opt end-1]} {
    lappend data [lindex $opt 0] [lindex $opt end]
    }
    }
    return $data
    }
    proc down(Clone) {w x y} {
    set current [$w find withtag current]
    if {[string length $current] > 0} {
    set itemData [serializeCanvasItem $w [$w find withtag current]]
    set ::ID [eval $w create $itemData]
    set ::X $x; set ::Y $y
    }
    }
    interp alias {} move(Clone) {} move(Move)
    #-- Drawing a rectangle
    proc down(Rect) {w x y} {
    set ::ID [$w create rect $x $y $x $y -fill $::Fill]
    }
    proc move(Rect) {w x y} {
    $w coords $::ID [lreplace [$w coords $::ID] 2 3 $x $y]
    }
    #-- Drawing an oval (or circle, if you're careful)
    proc down(Oval) {w x y} {
    set ::ID [$w create oval $x $y $x $y -fill $::Fill]
    }
    proc move(Oval) {w x y} {
    $w coords $::ID [lreplace [$w coords $::ID] 2 3 $x $y]
    }

    Polygons are drawn by clicking the corners. When a corner is close enough to the first one, the polygon is closed and drawn.

    proc down(Poly) {w x y} {
    if [info exists ::Poly] {
    set coords [$w coords $::Poly]
    foreach {x0 y0} $coords break
    if {hypot($y-$y0,$x-$x0)<10} {
    $w delete $::Poly
    $w create poly [lrange $coords 2 end] -fill $::Fill
    unset ::Poly
    } else {
    $w coords $::Poly [concat $coords $x $y]
    }
    } else {
    set ::Poly [$w create line $x $y $x $y -fill $::Fill]
    }
    }
    proc move(Poly) {w x y} {#nothing}
    #-- With little more coding, the Fill mode allows changing an item's fill color:
    proc down(Fill) {w x y} {$w itemconfig current -fill $::Fill}
    proc move(Fill) {w x y} {}
    #-- Building the UI
    set modes {Draw Move Clone Fill Rect Oval Poly}
    set colors {
    black white magenta brown red orange yellow green green3 green4
    cyan blue blue4 purple
    }
    grid [radio .1 Mode $modes] [radio .2 Fill $colors 1] -sticky nw
    grid [canvas .c -relief raised -borderwidth 1] - -sticky news
    grid rowconfig . 0 -weight 0
    grid rowconfig . 1 -weight 1
    #-- The current mode is retrieved at runtime from the global Mode variable:
    bind .c <1> {down($Mode) %W %x %y}
    bind .c <B1-Motion> {move($Mode) %W %x %y}
    bind .c <3> {%W delete current}

    For saving the current image, you need the Img extension, so just omit the following binding if you don't have Img:

    bind . <F1> {
    package require Img
    set img [image create photo -data .c]
    set name [tk_getSaveFile -filetypes {{GIFF .gif} {"All files" *}}\
    -defaultextension .gif]
    if {$name ne ""} {$img write $name; wm title . $name}
    }
    #-- This is an always useful helper in development:
    bind . <Escape> {exec wish $argv0 &; exit}

    [edit] A minimal editor

    Here's an utterly simple editor, in 26 lines of code, which just allows to load and save files, and of course edit, and cut and paste, and whatever is built-in into the text widget anyway. And it has a bit "online help"... ;-)

    It is always a good idea to start a source file with some explanations on the name, purpose, author, and date. I have recently picked up the habit to put this information into a string variable (which in Tcl can easily span multiple lines), so the same info is presented to the reader of the source code, and can be displayed as online help: }

    set about "minEd - a minimal editor
    Richard Suchenwirth 2003
    F1: help
    F2: load
    F3: save
    "

    The visible part of a Graphical User Interface (GUI) consists of widgets. For this editor, I of course need a text widget, and a vertical scrollbar. With the option "-wrap word" for the text widget, another horizontal scrollbar is not needed - lines longer than the window just wrap at word boundaries.

    Tk widgets come on the screen in two steps: first, they are created with an initial configuration; then, handed to a "geometry manager" for display. As widget creation commands return the pathname, they can be nested into the manager command (pack in this case), to keep all settings for a widget in one place. This may lead to over-long lines, though.

    Although the scrollbar comes to the right of the text, I create and pack it first. The reason is that when a window is made smaller by the user, the widgets last packed first lose visibility.

    These two lines also illustrate the coupling between a scrollbar and the widget it controls:

    • the scrollbar sends a yview message to it when moved
    • the widget sends a set message to the scrollbar when the view changed, for instance from cursor keys

    And these two lines already give us an editor for arbitrarily long text, with built-in capabilities of cut, copy, and paste - see the text man page. Only file I/O has to be added by us to make it really usable.

    pack [scrollbar .y -command ".t yview"] -side right -fill y
    pack [text .t -wrap word -yscrollc ".y set"] -side right -fill both -expand 1

    Are you targetting 8.4 or later? If so, add -undo 1 to the options to text and get full undo/redo support!

    pack [text .t -wrap word -yscrollc ".y set" -undo 1] -side right -fill both -expand 1

    The other important part of a GUI are the bindings - what event shall trigger what action. For simplicity, I've limited the bindings here to a few of the function keys on top of typical keyboards:

    bind . <F1> {tk_messageBox -message $about}

    Online help is done with a no-frills tk_messageBox with the "about" text defined at start of file. - The other bindings call custom commands, which get a filename argument from Tk's file selector dialogs:

    bind . <F2> {loadText .t [tk_getOpenFile]}
    bind . <F3> {saveText .t [tk_getSaveFile]}

    These dialogs can also be configured in a number of ways, but even in this simple form they are quite powerful - allow navigation around the file system, etc. On Windows they call the native file selectors, which have a history of previously opened files, detail view (size/date etc.)

    When this editor is called with a filename on the command line, that file is loaded on startup (simple as it is, it can only handle one file at a time):

    if {$argv != ""} {loadText .t [lindex $argv 0]}

    The procedures for loading and saving text both start with a sanity check of the filename argument - if it's an empty string, as produced by file selector dialogs when the user cancels, they return immediately. Otherwise, they transfer file content to text widget or vice-versa. loadText adds the "luxury" that the name of the current file is also put into the window title. Then it opens the file, clears the text widget, reads all file contents in one go, and puts them into the text widget.

    proc loadText {w fn} {
    if {$fn==""} return
    wm title . [file tail $fn]
    set fp [open $fn]
    $w delete 1.0 end
    $w insert end [read $fp]
    close $fp
    }

    saveText takes care not to save the extra newline that text widgets append at end, by limiting the range to "end - 1 c"(haracter).

    proc saveText {w fn} {
    if {$fn==""} return
    set fp [open $fn w]
    puts -nonewline $fp [$w get 1.0 "end - 1 c"]
    close $fp
    }

    [edit] File watch

    Some editors (e.g. PFE, MS Visual Studio) pop up an alert dialog when a file was changed on disk while being edited - that might lead to edit conflicts. Emacs shows a more subtle warning at the first attempt to change a file that has changed on disk.

    Here I try to emulate this feature. It is oversimplified because it does not update the mtime (file modification time) to check, once you saved it from the editor itself. So make sure to call text'watch'file again after saving.

    Using the global variable ::_twf it is at least possible to avoid false alarms - for a more serious implementation one might use a namespaced array of watchers, indexed by file name, in case you want multiple edit windows. }

    proc text'watch'file {w file {mtime -}} {
    set checkinterval 1000 ;# modify as needed
    if {$mtime eq "-"} {
    if [info exists ::_twf] {after cancel $::_twf}
    set file [file join [pwd] $file]
    text'watch'file $w $file [file mtime $file]
    } else {
    set newtime [file mtime $file]
    if {$newtime != $mtime} {
    set answer [tk_messageBox -type yesno -message \
    "The file\n$file\nhas changed on disk. Reload it?"]
    if {$answer eq "yes"} {text'read'file $w $file}
    text'watch'file $w $file
    } else {set ::_twf [after $checkinterval [info level 0]]}
    }
    }
    proc text'read'file {w file} {
    set f [open $file]
    $w delete 1.0 end
    $w insert end [read $f]
    close $f
    }
    #-- Testing:
    pack [text .t -wrap word] -fill both -expand 1
    set file textwatch.tcl
    text'read'file .t $file
    text'watch'file .t $file

    The dialog should come up when you change the file externally, say by touch-ing it in pure Tcl, which might be done with editing it in another editor, or

    file mtime $filename [clock seconds]

    [edit] Tiny presentation graphics

    This is a crude little canvas presentation graphics that runs on PocketPCs, but also on bigger boxes (one might scale fonts and dimensions there). Switch pages with Left/Right cursor, or left/right mouseclick (though a stylus cannot right-click).

    Not many features, but the code is very compact, and with a cute little language for content specification, see example at end (which shows what I presented at the 2003 Euro-Tcl convention in Nuremberg...)}

    proc slide args {
    global slides
    if {![info exist slides]} slide'init
    incr slides(N)
    set slides(title,$slides(N)) [join $args]
    }
    proc slide'line {type args} {
    global slides
    lappend slides(body,$slides(N)) [list $type [join $args]]
    }
    foreach name {* + -} {interp alias {} $name {} slide'line $name}
    proc slide'init {} {
    global slides
    array set slides {
    canvas .c N 0 show 1 dy 20
    titlefont {Tahoma 22 bold} * {Tahoma 14 bold} + {Tahoma 12}
    - {Courier 10}
    }
    pack [canvas .c -bg white] -expand 1 -fill both
    foreach e {<1> <Right>} {bind . $e {slide'show 1}}
    foreach e {<3> <Left>} {bind . $e {slide'show -1}}
    wm geometry . +0+0
    after idle {slide'show 0}
    }
    proc slide'show delta {
    upvar #0 slides s
    incr s(show) $delta
    if {$s(show)<1 || $s(show)>$s(N)} {
    incr s(show) [expr -$delta]
    } else {
    set c $s(canvas)
    $c delete all
    set x 10; set y 20
    $c create text $x $y -anchor w -text $s(title,$s(show))\
    -font $s(titlefont) -fill blue
    incr y $s(dy)
    $c create line $x $y 2048 $y -fill red -width 4
    foreach line $s(body,$s(show)) {
    foreach {type text} $line break
    incr y $s(dy)
    $c create text $x $y -anchor w -text $text \
    -font $s($type)
    }
    }
    }
    bind . <Up> {exec wish $argv0 &; exit} ;# dev helper

    The rest is data - or is it code? Anyway, here's my show:

    slide i18n - Tcl for the world
    + Richard Suchenwirth, Nuremberg 2003
    +
    * i18n: internationalization
    + 'make software work with many languages'
    +
    * l10n: localization
    + 'make software work with the local language'
    slide Terminology
    * Glyphs:
    + visible elements of writing
    * Characters:
    + abstract elements of writing
    * Byte sequences:
    + physical text data representation
    * Rendering: character -> glyph
    * Encoding: character <-> byte sequence
    slide Before Unicode
    * Bacon (1580), Baudot: 5-bit encodings
    * Fieldata (6 bits), EBCDIC (8 bits)
    * ASCII (7 bits)
    + world-wide "kernel" of encodings
    * 8-bit codepages: DOS, Mac, Windows
    * ISO 8859-x: 16 varieties
    slide East Asia
    * Thousands of characters/country
    + Solution: use 2 bytes, 94x94 matrix
    + Japan: JIS C-6226/0208/0212
    + China: GB2312-80
    + Korea: KS-C 5601
    +
    * coexist with ASCII in EUC encodings
    slide Unicode covers all
    * Common standard of software industry
    * kept in synch with ISO 10646
    + Used to be 16 bits, until U 3.1
    + Now needs up to 31 bits
    * Byte order problem:
    + little-endian/big-endian
    + U+FEFF "Byte Order Mark"
    + U+FFFE --illegal--
    slide UTF-8
    * Varying length: 1..3(..6) bytes
    + 1 byte: ASCII
    + 2 bytes: pages 00..07, Alphabets
    + 3 bytes: pages 08..FF, rest of BMP
    + >3 bytes: higher pages
    +
    * Standard in XML, coming in Unix
    slide Tcl i18n
    * Everything is a Unicode string (BMP)
    + internal rep: UTF-8/UCS-2
    * Important commands:
    - fconfigure \$ch -encoding \$e
    - encoding convertfrom \$e \$s
    - encoding convertto \$e \$s
    +
    * msgcat supports l10n:
    - {"File" -> [mc "File"]}
    slide Tk i18n
    * Any widget text is Unicoded
    * Automatic font finding
    + Fonts must be provided by system
    +
    * Missing: bidi treatment
    + right-to-left conversion (ar,he)
    slide Input i18n
    * Keyboard rebinding (bindtags)
    * East Asia: keyboard buffering
    + Menu selection for ambiguities
    +
    * Virtual keyboard (buttons, canvas)
    * String conversion: *lish family
    - {[ruslish Moskva]-[greeklish Aqh'nai]}
    slide i18n - Tcl for the world
    +
    +
    + Thank you.

    [edit] Timeline display

    Yet another thing to do with a canvas: history visualisation of a horizontal time-line, for which a year scale is displayed on top. The following kinds of objects are so far available:

    • "eras", displayed in yellow below the timeline in boxes
    • "background items" that are grey and stretch over all the canvas in height
    • normal items, which get displayed as stacked orange bars

    Image:Timeliner.jpg

    You can zoom in with <1>, out with <3> (both only in x direction). On mouse motion, the current year is displayed in the toplevel's title. Normal items can be a single year, like the Columbus example, or a range of years, for instance for lifetimes of persons. (The example shows that Mozart didn't live long...)

    namespace eval timeliner {
    variable ""
    array set "" {-zoom 1 -from 0 -to 2000}
    }
    proc timeliner::create {w args} {
    variable ""
    array set "" $args
    #-- draw time scale
    for {set x [expr ($(-from)/50)*50]} {$x<=$(-to)} {incr x 10} {
    if {$x%50 == 0} {
    $w create line $x 8 $x 0
    $w create text $x 8 -text $x -anchor n
    } else {
    $w create line $x 5 $x 0
    }
    }
    bind $w <Motion> {timeliner::title %W %x ; timeliner::movehair %W %x}
    bind $w <1> {timeliner::zoom %W %x 1.25}
    bind $w <2> {timeliner::hair %W %x}
    bind $w <3> {timeliner::zoom %W %x 0.8}
    }
    proc timeliner::movehair {w x} {
    variable ""
    if {[llength [$w find withtag hair]]} {
    set x [$w canvasx $x]
    $w move hair [expr {$x - $(x)}] 0
    set (x) $x
    }
    }
    proc timeliner::hair {w x} {
    variable ""
    if {[llength [$w find withtag hair]]} {
    $w delete hair
    } else {
    set (x) [$w canvasx $x]
    $w create line $(x) 0 $(x) [$w cget -height] \
    -tags hair -width 1 -fill red
    }
    }
    proc timeliner::title {w x} {
    variable ""
    wm title . [expr int([$w canvasx $x]/$(-zoom))]
    }
    proc timeliner::zoom {w x factor} {
    variable ""
    $w scale all 0 0 $factor 1
    set (-zoom) [expr {$(-zoom)*$factor}]
    $w config -scrollregion [$w bbox all]
    if {[llength [$w find withtag hair]]} {
    $w delete hair
    set (x) [$w canvasx $x]
    $w create line $(x) 0 $(x) [$w cget -height] \
    -tags hair -width 1 -fill red
    }
    }

    This command adds an object to the canvas. The code for "item" took me some effort, as it had to locate a free "slot" on the canvas, searching top-down:

    proc timeliner::add {w type name time args} {
    variable ""
    regexp {(\d+)(-(\d+))?} $time -> from - to
    if {$to eq ""} {set to $from}
    set x0 [expr {$from*$(-zoom)}]
    set x1 [expr {$to*$(-zoom)}]
    switch -- $type {
    era {set fill yellow; set outline black; set y0 20; set y1 40}
    bgitem {set fill gray; set outline {}; set y0 40; set y1 1024}
    item {
    set fill orange
    set outline yellow
    for {set y0 60} {$y0<400} {incr y0 20} {
    set y1 [expr {$y0+18}]
    if {[$w find overlap [expr $x0-5] $y0 $x1 $y1] eq ""} break
    }
    }
    }
    set id [$w create rect $x0 $y0 $x1 $y1 -fill $fill -outline $outline]
    if {$type eq "bgitem"} {$w lower $id}
    set x2 [expr {$x0+5}]
    set y2 [expr {$y0+2}]
    set tid [$w create text $x2 $y2 -text $name -anchor nw]
    foreach arg $args {
    if {$arg eq "!"} {
    $w itemconfig $tid -font "[$w itemcget $tid -font] bold"
    }
    }
    $w config -scrollregion [$w bbox all]
    }

    Here's a sample application, featuring a concise history of music in terms of composers:

    scrollbar .x -ori hori -command {.c xview}
    pack .x -side bottom -fill x
    canvas .c -bg white -width 600 -height 300 -xscrollcommand {.x set}
    pack .c -fill both -expand 1
    timeliner::create .c -from 1400 -to 2000

    These nifty shorthands for adding items make data specification a breeze - compare the original call, and the shorthand:

       timeliner::add .c item Purcell 1659-1695
    - Purcell 1659-1695

    With an additional "!" argument you can make the text of an item bold:

    foreach {shorthand type} {* era  x bgitem - item} {
    interp alias {} $shorthand {} timeliner::add .c $type
    }

    Now for the data to display (written pretty readably):

    * {Middle Ages} 1400-1450
    - Dufay 1400-1474
    * Renaissance 1450-1600
    - Desprez 1440-1521
    - Luther 1483-1546
    - {Columbus discovers America} 1492
    - Palestrina 1525-1594 !
    - Lasso 1532-1594
    - Byrd 1543-1623
    * Baroque 1600-1750
    - Dowland 1563-1626
    - Monteverdi 1567-1643
    - Schütz 1585-1672
    - Purcell 1659-1695
    - Telemann 1681-1767
    - Rameau 1683-1764
    - Bach,J.S. 1685-1750 !
    - Händel 1685-1759
    x {30-years war} 1618-1648
    * {Classic era} 1750-1810
    - Haydn 1732-1809 !
    - Boccherini 1743-1805
    - Mozart 1756-1791 !
    - Beethoven 1770-1828 !
    * {Romantic era} 1810-1914
    - {Mendelssohn Bartholdy} 1809-1847
    - Chopin 1810-1849
    - Liszt 1811-1886
    - Verdi 1813-1901
    x {French revolution} 1789-1800
    * {Modern era} 1914-2000
    - Ravel 1875-1937 !
    - Bartók 1881-1945
    - Stravinskij 1882-1971
    - Varèse 1883-1965
    - Prokof'ev 1891-1953
    - Milhaud 1892-1974
    - Honegger 1892-1955
    - Hindemith 1895-1963
    - Britten 1913-1976
    x WW1 1914-1918
    x WW2 1938-1945

    [edit] Fun with functions

    Image:funplot.jpg

    My teenage daughter hates math. In order to motivate her, I beefed up an earlier little function plotter which before only took one function, in strict Tcl (expr) notation, from the command line. Now there's an entry widget, and the accepted language has also been enriched: beyond exprs rules, you can omit dollar and multiplication signs, like 2x+1, powers can be written as x3 instead of ($x*$x*$x); in simple cases you can omit parens round function arguments, like sin x2. Hitting <Return> in the entry widget displays the function's graph.

    If you need some ideas, click on the "?" button to cycle through a set of demo functions, from boring to bizarre (e.g. if rand() is used). Besides default scaling, you can zoom in or out. Moving the mouse pointer over the canvas displays x and y coordinates, and the display changes to white if you're on a point on the curve.

    The target was not reached: my daughter still hates math. But at least I had hours of Tcl (and function) fun again, surfing in the Cartesian plane... hope you enjoy it too!

    proc main {} {
    canvas .c -bg white -borderwidth 0
    bind .c <Motion> {displayXY .info %x %y}
    frame .f
    label .f.1 -text "f(x) = "
    entry .f.f -textvar ::function -width 40
    bind .f.f <Return> {plotf .c $::function}
    button .f.demo -text " ? " -pady 0 -command {demo .c}
    label .f.2 -text " Zoom: "
    entry .f.fac -textvar ::factor -width 4
    set ::factor 32
    bind .f.fac <Return> {zoom .c 1.0}
    button .f.plus -text " + " -pady 0 -command {zoom .c 2.0}
    button .f.minus -text " - " -pady 0 -command {zoom .c 0.5}
    eval pack [winfo children .f] -side left -fill both
    label .info -textvar ::info -just left
    pack .info .f -fill x -side bottom
    pack .c -fill both -expand 1
    demo .c
    }
    set ::demos {
    "cos x3" 2 1-x 0.5x2 x3/5 "sin x" "sin x2" 1/x sqrt(x)
    "tan x/5" x+1/x x abs(x) "exp x" "log x" "log x2"
    round(x) "int x%2" "x-int x" "0.2tan x+1/tan x" x*(rand()-0.5)
    x2/5-1/(2x) "atan x" sqrt(1-x2) "abs(x-int(x*2))" (x-1)/(x+1)
    "sin x-tan x" "sin x-tan x2" "x-abs(int x)" 0.5x-1/x
    -0.5x3+x2+x-1 3*sin(2x) -0.05x4-0.2x3+1.5x2+2x-3 "9%int x"
    0.5x2/(x3-3x2+4) "abs x2-3 int x" "int x%3"
    }
    proc displayXY {w cx cy} {
    set x [expr {double($cx-$::dx)/$::factor}]
    set y [expr {double(-$cy+$::dy)/$::factor}]
    set ::info [format "x=%.2f y=%.2f" $x $y]
    catch {
    $w config -fg [expr {abs([expr $::fun]-$y)<0.01?"white":"black"}]
    } ;# may divide by zero, or other illegal things
    }
    proc zoom {w howmuch} {
    set ::factor [expr round($::factor*$howmuch)]
    plotf $w $::function
    }
    proc plotf {w function} {
    foreach {re subst} {
    {([a-z]) +(x[0-9]?)} {\1(\2)} " " "" {([0-9])([a-z])} {\1*\2}
    x2 x*x x3 x*x*x x4 x*x*x*x x \$x {e\$xp} exp
    } {regsub -all $re $function $subst function}
    set ::fun $function
    set ::info "Tcl: expr $::fun"
    set color [lpick {red blue purple brown green}]
    plotline $w [fun2points $::fun] -fill $color
    }
    proc lpick L {lindex $L [expr {int(rand()*[llength $L])}]}
    proc fun2points {fun args} {
    array set opt {-from -10.0 -to 10.0 -step .01}
    array set opt $args
    set res "{"
    for {set x $opt(-from)} {$x<= $opt(-to)} {set x [expr {$x+$opt(-step)}]} {
    if {![catch {expr $fun} y]} {
    if {[info exists lasty] && abs($y-$lasty)>100} {
    append res "\} \{" ;# incontinuity
    }
    append res " $x $y"
    set lasty $y
    } else {append res "\} \{"}
    }
    append res "}"
    }
    proc plotline {w points args} {
    $w delete all
    foreach i $points {
    if {[llength $i]>2} {eval $w create line $i $args -tags f}
    }
    set fac $::factor
    $w scale all 0 0 $fac -$fac
    $w create line -10000 0 10000 0 ;# X axis
    $w create line 0 -10000 0 10000 ;# Y axis
    $w create line $fac 0 $fac -3 ;# x=1 tick
    $w create line -3 -$fac 0 -$fac ;# y=1 tick
    set ::dx [expr {[$w cget -width]/2}]
    set ::dy [expr {[$w cget -height]/2}]
    $w move all $::dx $::dy
    $w raise f
    }
    proc demo {w} {
    set ::function [lindex $::demos 0] ;# cycle through...
    set ::demos [concat [lrange $::demos 1 end] [list $::function]]
    set ::factor 32
    plotf $w $::function
    }
    main

    [edit] Functional imaging

    In Conal Elliott's Pan project ("Functional Image Synthesis", [1]), images (of arbitrary size and resolution) are produced and manipulated in an elegant functional way. Functions written in Haskell (see Playing Haskell) are applied, mostly in functional composition, to pixels to return their color value. FAQ: "Can we have that in Tcl too?"

    Image:funimj.jpg

    As the funimj demo below shows, in principle yes; but it takes some patience (or a very fast CPU) - for a 200x200 image the function is called 40000 times, which takes 9..48 seconds on my P200 box. Still, the output often is worth waiting for... and the time used to write this code was negligible, as the Haskell original could with few modifications be represented in Tcl. Functional composition had to be rewritten to Tcl's Polish notation - Haskell's

    foo 1 o bar 2 o grill

    (where "o" is the composition operator) would in Tcl look like

    o {foo 1} {bar 2} grill

    As the example shows, additional arguments can be specified; only the last argument is passed through the generated "function nest":

    proc f {x} {foo 1 [bar 2 [grill $x]]}

    But the name of the generated function is much nicer than "f": namely, the complete call to "o" is used, so the example proc has the name

    "o {foo 1} {bar 2} grill"

    which is pretty self-documenting ;-) I implemented "o" like this:

    proc o args {
    # combine the functions in args, return the created name
    set name [info level 0]
    set body "[join $args " \["] \$x"
    append body [string repeat \] [expr {[llength $args]-1}]]
    proc $name x $body
    set name
    }
    # Now for the rendering framework:
    proc fim {f {zoom 100} {width 200} {height -}} {
    # produce a photo image by applying function f to pixels
    if {$height=="-"} {set height $width}
    set im [image create photo -height $height -width $width]
    set data {}
    set xs {}
    for {set j 0} {$j<$width} {incr j} {
    lappend xs [expr {($j-$width/2.)/$zoom}]
    }
    for {set i 0} {$i<$height} {incr i} {
    set row {}
    set y [expr {($i-$height/2.)/$zoom}]
    foreach x $xs {
    lappend row [$f [list $x $y]]
    }
    lappend data $row
    }
    $im put $data
    set im
    }

    Basic imaging functions ("drawers") have the common functionality point -> color, where point is a pair {x y} (or, after applying a polar transform, {r a}...) and color is a Tk color name, like "green" or #010203:

    proc  vstrip p {
    # a simple vertical bar
    b2c [expr {abs([lindex $p 0]) < 0.5}]
    }
    proc udisk p {
    # unit circle with radius 1
    foreach {x y} $p break
    b2c [expr {hypot($x,$y) < 1}]
    }
    proc xor {f1 f2 p} {
    lappend f1 $p; lappend f2 $p
    b2c [expr {[eval $f1] != [eval $f2]}]
    }
    proc and {f1 f2 p} {
    lappend f1 $p; lappend f2 $p
    b2c [expr {[eval $f1] == "#000" && [eval $f2] == "#000"}]
    }
    proc checker p {
    # black and white checkerboard
    foreach {x y} $p break
    b2c [expr {int(floor($x)+floor($y)) % 2 == 0}]
    }
    proc gChecker p {
    # greylevels correspond to fractional part of x,y
    foreach {x y} $p break
    g2c [expr {(fmod(abs($x),1.)*fmod(abs($y),1.))}]
    }
    proc bRings p {
    # binary concentric rings
    foreach {x y} $p break
    b2c [expr {round(hypot($x,$y)) % 2 == 0}]
    }
    proc gRings p {
    # grayscale concentric rings
    foreach {x y} $p break
    g2c [expr {(1 + cos(3.14159265359 * hypot($x,$y))) / 2.}]
    }
    proc radReg {n p} {
    # n wedge slices starting at (0,0)
    foreach {r a} [toPolars $p] break
    b2c [expr {int(floor($a*$n/3.14159265359))%2 == 0}]
    }
    proc xPos p {b2c [expr {[lindex $p 0]>0}]}
    proc cGrad p {
    # color gradients - best watched at zoom=100
    foreach {x y} $p break
    if {abs($x)>1.} {set x 1.}
    if {abs($y)>1.} {set y 1.}
    set r [expr {int((1.-abs($x))*255.)}]
    set g [expr {int((sqrt(2.)-hypot($x,$y))*180.)}]
    set b [expr {int((1.-abs($y))*255.)}]
    c2c $r $g $b
    }

    Beyond the examples in Conal Elliott's paper, I found out that function imaging can also be abused for a (slow and imprecise) function plotter, which displays the graph for y = f(x) if you call it with $y + f($x) as first argument:

    proc fplot {expr p} {
    foreach {x y} $p break
    b2c [expr abs($expr)<=0.04] ;# double eval required here!
    }

    Here is a combinator for two binary images that shows in different colors for which point both or either are "true" - nice but slow:}

    proc bin2 {f1 f2 p} {
    set a [eval $f1 [list $p]]
    set b [eval $f2 [list $p]]
    expr {
    $a == "#000" ?
    $b == "#000" ? "green"
    : "yellow"
    : $b == "#000" ? "blue"
    : "black"
    }
    }
    #--------------------------------------- Pixel converters:
    proc g2c {greylevel} {
    # convert 0..1 to #000000..#FFFFFF
    set hex [format %02X [expr {round($greylevel*255)}]]
    return #$hex$hex$hex
    }
    proc b2c {binpixel} {
    # 0 -> white, 1 -> black
    expr {$binpixel? "#000" : "#FFF"}
    }
    proc c2c {r g b} {
    # make Tk color name: {0 128 255} -> #0080FF
    format #%02X%02X%02X $r $g $b
    }
    proc bPaint {color0 color1 pixel} {
    # convert a binary pixel to one of two specified colors
    expr {$pixel=="#000"? $color0 : $color1}
    }

    This painter colors a grayscale image in hues of the given color. It normalizes the given color through dividing by the corresponding values for "white", but appears pretty slow too:

    proc gPaint {color pixel} {
    set abspixel [lindex [rgb $pixel] 0]
    set rgb [rgb $color]
    set rgbw [rgb white]
    foreach var {r g b} in $rgb ref $rgbw {
    set $var [expr {round(double($abspixel)*$in/$ref/$ref*255.)}]
    }
    c2c $r $g $b
    }

    This proc caches the results of [winfo rgb] calls, because these are quite expensive, especially on remote X displays - rmax

    proc rgb {color} {
    upvar "#0" rgb($color) rgb
    if {![info exists rgb]} {set rgb [winfo rgb . $color]}
    set rgb
    }
    #------------------------------ point -> point transformers
    proc fromPolars p {
    foreach {r a} $p break
    list [expr {$r*cos($a)}] [expr {$r*sin($a)}]
    }
    proc toPolars p {
    foreach {x y} $p break
    # for Sun, we have to make sure atan2 gets no two 0's
    list [expr {hypot($x,$y)}] [expr {$x||$y? atan2($y,$x): 0}]
    }
    proc radInvert p {
    foreach {r a} [toPolars $p] break
    fromPolars [list [expr {$r? 1/$r: 9999999}] $a]
    }
    proc rippleRad {n s p} {
    foreach {r a} [toPolars $p] break
    fromPolars [list [expr {$r*(1.+$s*sin($n*$a))}] $a]
    }
    proc slice {n p} {
    foreach {r a} $p break
    list $r [expr {$a*$n/3.14159265359}]
    }
    proc rotate {angle p} {
    foreach {x y} $p break
    set x1 [expr {$x*cos(-$angle) - $y*sin(-$angle)}]
    set y1 [expr {$y*cos(-$angle) + $x*sin(-$angle)}]
    list $x1 $y1
    }
    proc swirl {radius p} {
    foreach {x y} $p break
    set angle [expr {hypot($x,$y)*6.283185306/$radius}]
    rotate $angle $p
    }

    Now comes the demo program. It shows the predefined basic image operators, and some combinations, on a button bar. Click on one, have some patience, and the corresponding image will be displayed on the canvas to the right. You can also experiment with image operators in the entry widget at bottom - hit <Return> to try. The text of sample buttons is also copied to the entry widget, so you can play with the parameters, or rewrite it as you wish. Note that a well-formed funimj composition consists of:

    • the composition operator "o"
    • zero or more "painters" (color -> color)
    • one "drawer" (point -> color)
    • zero or more "transformers" (point -> point)

    }

    proc fim'show {c f} {
    $c delete all
    set ::try $f ;# prepare for editing
    set t0 [clock seconds]
    . config -cursor watch
    update ;# to make the cursor visible
    $c create image 0 0 -anchor nw -image [fim $f $::zoom]
    wm title . "$f: [expr [clock seconds]-$t0] seconds"
    . config -cursor {}
    }
    proc fim'try {c varName} {
    upvar #0 $varName var
    $c delete all
    if [catch {fim'show $c [eval $var]}] {
    $c create text 10 10 -anchor nw -text $::errorInfo
    }
    }

    Composed functions need only be mentioned once, which creates them, and they can later be picked up by info procs. The o looks nicely bullet-ish here..

    o bRings
    o cGrad
    o checker
    o gRings
    o vstrip
    o xPos
    o {bPaint brown beige} checker
    o checker {slice 10} toPolars
    o checker {rotate 0.1}
    o vstrip {swirl 1.5}
    o checker {swirl 16}
    o {fplot {$y + exp($x)}}
    o checker radInvert
    o gRings {rippleRad 8 0.3}
    o xPos {swirl .75}
    o gChecker
    o {gPaint red} gRings
    o {bin2 {radReg 7} udisk}
    #----------------------------------------------- testing
    frame .f2
    set c [canvas .f2.c]
    set e [entry .f2.e -bg white -textvar try]
    bind $e <Return> [list fim'try $c ::try]
    scale .f2.s -from 1 -to 100 -variable zoom -ori hori -width 6
    #--------------------------------- button bar:
    frame .f
    set n 0
    foreach imf [lsort [info procs "o *"]] {
    button .f.b[incr n] -text $imf -anchor w -pady 0 \
    -command [list fim'show $c $imf]
    }
    set ::zoom 25
    eval pack [winfo children .f] -side top -fill x -ipady 0
    eval pack [winfo children .f2] -side top -fill x
    pack .f .f2 -side left -anchor n
    bind . <Escape> {exec wish $argv0 &; exit} ;# dev helper
    bind . ? {console show} ;# dev helper, Win/Mac only

    [edit] TkPhotoLab

    The following code can be used for experiments in image processing, including

    • convolutions (see below)
    • conversion from color to greylevel
    • conversion from greylevel to faux color
    • brightness and contrast modification

    Tcl is not the fastest in heavy number-crunching, as needed when going over many thousands of pixels, but I wouldn't consider C for a fun project ;) So take your time, or get a real CPU. At least you can watch the progress, as the target image is updated after every row.

    Image:TkPhotoLab.jpg

    Edge enhancement by Laplace5 filter

    The demo UI shows two images, the original on the left, the processing result on the right. You can push the result to the left with Options/Accept. See the menus for what goodies I have supplied. But what most interested me were "convolutions", for which you can edit the matrix (fixed at 3x3 - slow enough..) and click "Apply" to run it over the input image. "C" to set the matrix to all zeroes.

    Convolution is a technique where a target pixel is colored according to the sum of the product of a given matrix and its neighbors. As an example, the convolution matrix

    1 1 1
    1 1 1
    1 1 1

    colors the pixel in the middle with the average of itself and its eight neighbors, which will myopically blur the picture.

    0 0 0
    0 1 0
    0 0 0

    should just faithfully repeat the input picture. These

    0  -1  0       -1 -1 -1
    -1 5 -1 or: -1 9 -1
    0 -1 0 -1 -1 -1

    enhance {horizont,vertic}al edges, and make the image look "crispier". }

    proc convolute {inimg outimg matrix} {
    set w [image width $inimg]
    set h [image height $inimg]
    set matrix [normalize $matrix]
    set shift [expr {[matsum $matrix]==0? 128: 0}]
    set imat [photo2matrix $inimg]
    for {set i 1} {$i<$h-1} {incr i} {
    set row {}
    for {set j 1} {$j<$w-1} {incr j} {
    foreach var {rsum gsum bsum} {set $var 0.0}
    set y [expr {$i-1}]
    foreach k {0 1 2} {
    set x [expr {$j-1}]
    foreach l {0 1 2} {
    if {[set fac [lindex $matrix $k $l]]} {
    foreach {r g b} [lindex $imat $y $x] {}
    set rsum [expr {$rsum + $r * $fac}]
    set gsum [expr {$gsum + $g * $fac}]
    set bsum [expr {$bsum + $b * $fac}]
    }
    incr x
    }
    incr y
    }
    if {$shift} {
    set rsum [expr {$rsum + $shift}]
    set gsum [expr {$gsum + $shift}]
    set bsum [expr {$bsum + $shift}]
    }
    lappend row [rgb [clip $rsum] [clip $gsum] [clip $bsum]]
    }
    $outimg put [list $row] -to 1 $i
    update idletasks
    }
    }
    proc alias {name args} {eval [linsert $args 0 interp alias {} $name {}]}
    alias rgb   format #%02x%02x%02x
    proc lambda {argl body} {K [set n [info level 0]] [proc $n $argl $body]}
    proc K      {a b} {set a}
    proc clip   x {expr {$x>255? 255: $x<0? 0: int($x)}}
    proc photo2matrix image {
    set w [image width $image]
    set h [image height $image]
    set res {}
    for {set y 0} {$y<$h} {incr y} {
    set row {}
    for {set x 0} {$x<$w} {incr x} {
    lappend row [$image get $x $y]
    }
    lappend res $row
    }
    set res
    }
    proc normalize matrix {
    #-- make sure all matrix elements add up to 1.0
    set sum [matsum $matrix]
    if {$sum==0} {return $matrix} ;# no-op on zero sum
    set res {}
    foreach inrow $matrix {
    set row {}
    foreach el $inrow {lappend row [expr {1.0*$el/$sum}]}
    lappend res $row
    }
    set res
    }
    proc matsum matrix {expr [join [join $matrix] +]}

    The following routines could also be generified into one:

    proc color2gray image {
    set w [image width $image]
    set h [image height $image]
    for {set i 0} {$i<$h} {incr i} {
    set row {}
    for {set j 0} {$j<$w} {incr j} {
    foreach {r g b} [$image get $j $i] break
    set y [expr {int(0.299*$r + 0.587*$g + 0.114*$b)}]
    lappend row [rgb $y $y $y]
    }
    $image put [list $row] -to 0 $i
    update idletasks
    }
    }
    proc color2gray2 image {
    set i -1
    foreach inrow [photo2matrix $image] {
    set row {}
    foreach pixel $inrow {
    foreach {r g b} $pixel break
    set y [expr {int(($r + $g + $b)/3.)}]
    lappend row [rgb $y $y $y]
    }
    $image put [list $row] -to 0 [incr i]
    update idletasks
    }
    }

    An experiment in classifying graylevels into unreal colors:

    proc gray2color image {
    set i -1
    set colors {black darkblue blue purple red orange yellow white}
    set n [llength $colors]
    foreach inrow [photo2matrix $image] {
    set row {}
    foreach pixel $inrow {
    set index [expr {[lindex $pixel 0]*$n/256}]
    lappend row [lindex $colors $index]
    }
    $image put [list $row] -to 0 [incr i]
    update idletasks
    }
    }
    proc grayWedge image {
    $image blank
    for {set i 0} {$i<256} {incr i} {
    $image put [rgb $i $i $i] -to $i 0 [expr {$i+1}] 127
    }
    }

    A number of algorithms are very similar, distinguished only by a few commands in the center. Hence I made them generic, and they take a function name that is applied to every pixel rgb, resp. a pair of pixel rgb's. They are instantiated by an alias that sets the function fancily as a lambda:

    proc generic_1 {f target source} {
    set w [image width $source]
    set h [image height $source]
    for {set i 0} {$i<$h} {incr i} {
    set row {}
    for {set j 0} {$j<$w} {incr j} {
    foreach {r g b} [$source get $j $i] break
    lappend row [rgb [$f $r] [$f $g] [$f $b]]
    }
    $target put [list $row] -to 0 $i
    update idletasks
    }
    }
    alias invert    generic_1 [lambda x {expr {255-$x}}]
    alias contrast+ generic_1 [lambda x {clip [expr {128+($x-128)*1.25}]}]
    alias contrast- generic_1 [lambda x {clip [expr {128+($x-128)*0.8}]}]
    proc generic_2 {f target with} {
    set w [image width $target]
    set h [image height $target]
    for {set i 0} {$i<$h} {incr i} {
    set row {}
    for {set j 0} {$j<$w} {incr j} {
    foreach {r g b} [$target get $j $i] break
    foreach {r1 g1 b1} [$with get $j $i] break
    lappend row [rgb [$f $r $r1] [$f $g $g1] [$f $b $b1]]
    }
    $target put [list $row] -to 0 $i
    update idletasks
    }
    }
    alias blend      generic_2 [lambda {a b} {expr {($a+$b)/2}}]
    alias difference generic_2 [lambda {a b} {expr {255-abs($a-$b)}}]

    A histogram is a count of which color value occurred how often in the current image, separately for red, green and blue. For graylevel images, the displayed "curves" should exactly overlap, so you see only the blue dots that are drawn last.

    proc histogram {image {channel 0}} {
    set w [image width $image]
    set h [image height $image]
    for {set i 0} {$i<256} {incr i} {set hist($i) 0}
    for {set i 0} {$i<$h} {incr i} {
    for {set j 0} {$j<$w} {incr j} {
    incr hist([lindex [$image get $j $i] $channel])
    }
    }
    set res {}
    for {set i 0} {$i<256} {incr i} {lappend res $hist($i)}
    set res
    }
    proc drawHistogram {target input} {
    $target blank
    set a [expr {6000./([image height $input]*[image width $input])}]
    foreach color {red green blue} channel {0 1 2} {
    set i -1
    foreach val [histogram $input $channel] {
    $target put $color -to [incr i] \
    [clip [expr {int(128-$val*$a)}]]
    }
    update idletasks
    }
    }

    Demo UI:

    if {[file tail [info script]] eq [file tail $argv0]} {
    package require Img ;# for JPEG etc.
    proc setFilter {w matrix} {
    $w delete 1.0 end
    foreach row $matrix {$w insert end [join $row \t]\n}
    set ::info "Click 'Apply' to use this filter"
    }
    label .title -text TkPhotoLab -font {Helvetica 14 italic} -fg blue
    label .( -text ( -font {Courier 32}
    set txt [text .t -width 20 -height 3]
    setFilter .t {{0 -1 0} {-1 5 -1} {0 -1 0}}
    label .) -text ) -font {Courier 32}
    button .c -text C -command {setFilter .t {{0 0 0} {0 0 0} {0 0 0}}}
    grid .title .( .t .) .c -sticky news
    button .apply -text Apply -command applyConv
    grid x ^ ^ ^ .apply -sticky ew
    grid [label .0 -textvar info] - - -sticky w
    grid [label .1] - [label .2] - - -sticky new
       proc loadImg { {fn ""}} {
    if {$fn==""} {set fn [tk_getOpenFile]}
    if {$fn != ""} {
    cd [file dirname [file join [pwd] $fn]]
    set ::im1 [image create photo -file $fn]
    .1 config -image $::im1
    set ::im2 [image create photo]
    .2 config -image $::im2
    $::im2 copy $::im1 -shrink
    set ::info "Loaded image 1 from $fn"
    }
    }
    proc saveImg { {fn ""}} {
    if {$fn==""} {set fn [tk_getSaveFile]}
    if {$fn != ""} {
    $::im2 write $fn -format JPEG
    set ::info "Saved image 2 to $fn"
    }
    }
    proc applyConv {} {
    set ::info "Convolution running, have patience..."
    set t0 [clock clicks -milliseconds]
    convolute $::im1 $::im2 [split [$::txt get 1.0 end] \n]
    set dt [expr {([clock click -milliseconds]-$t0)/1000.}]
    set ::info "Ready after $dt sec"
    }

    A little wrapper for simplified menu creation - see below for its use:

       proc m+ {head name {cmd ""}} {
    if {![winfo exists .m.m$head]} {
    .m add cascade -label $head -menu [menu .m.m$head -tearoff 0]
    }
    if [regexp ^-+$ $name] {
    .m.m$head add separator
    } else {.m.m$head add command -label $name -comm $cmd}
    }
       . config -menu [menu .m]
    m+ File Open.. loadImg
    m+ File Save.. saveImg
    m+ File ---
    m+ File Exit exit
       m+ Edit Blend      {blend $im2 $im1}
    m+ Edit Difference {difference $im2 $im1}
    m+ Edit ---
    m+ Edit Negative {invert $im2 $im1}
    m+ Edit Contrast+ {contrast+ $im2 $im1}
    m+ Edit Contrast- {contrast- $im2 $im1}
    m+ Edit ---
    m+ Edit Graylevel {$im2 copy $im1 -shrink; color2gray $im2}
    m+ Edit Graylevel2 {$im2 copy $im1 -shrink; color2gray2 $im2}
    m+ Edit "Add Noise" {
    generic_1 [lambda x {expr {rand()<.01? int(rand()*255):$x}}] $im2 $im1
    }
    m+ Edit gray2color {$im2 copy $im1 -shrink; gray2color $im2}
    m+ Edit Octary {generic_1 [lambda x {expr {$x>127? 255:0}}] $im2 $im1}
    m+ Edit ---
    m+ Edit HoriMirror {$im2 copy $im1 -shrink -subsample -1 1}
    m+ Edit VertMirror {$im2 copy $im1 -shrink -subsample 1 -1}
    m+ Edit "Upside down" {$im2 copy $im1 -shrink -subsample -1 -1}
    m+ Edit ---
    m+ Edit "Zoom x 2" {$im2 copy $im1 -shrink -zoom 2}
    m+ Edit "Zoom x 3" {$im2 copy $im1 -shrink -zoom 3}
       m+ Options "Accept (1<-2)" {$im1 copy $im2 -shrink}
    m+ Options ---
    m+ Options "Gray wedge" {grayWedge $im2}
    m+ Options Histogram {drawHistogram $im2 $im1}
       m+ Filter Clear {setFilter .t {{0 0 0} {0 0 0} {0 0 0}}}
    m+ Filter ---
    m+ Filter Blur0 {setFilter .t {{1 1 1} {1 0 1} {1 1 1}}}
    m+ Filter Blur1 {setFilter .t {{1 1 1} {1 1 1} {1 1 1}}}
    m+ Filter Gauss2 {setFilter .t {{1 2 1} {2 4 2} {1 2 1}}}
    m+ Filter ---
    m+ Filter Laplace5 {setFilter .t {{0 -1 0} {-1 5 -1} {0 -1 0}}}
    m+ Filter Laplace9 {setFilter .t {{-1 -1 -1} {-1 9 -1} {-1 -1 -1}}}
    m+ Filter LaplaceX {setFilter .t {{1 -2 1} {-2 5 -2} {1 -2 1}}}
    m+ Filter ---
    m+ Filter Emboss {setFilter .t {{2 0 0} {0 -1 0} {0 0 -1}}}
    m+ Filter HoriEdge {setFilter .t {{-1 -1 -1} {0 0 0} {1 1 1}}}
    m+ Filter VertEdge {setFilter .t {{-1 0 1} {-1 0 1} {-1 0 1}}}
    m+ Filter SobelH {setFilter .t {{1 2 1} {0 0 0} {-1 -2 -1}}}
    m+ Filter SobelV {setFilter .t {{1 0 -1} {2 0 -2} {1 0 -1}}}
       bind . <Escape> {exec wish $argv0 &; exit}
    bind . <F1> {console show}
    loadImg aaa.jpg
    }
  •  07-29-2009, 10:00 AM 8496 in reply to 7931

    Weird clock format in Tcl/Tk Programming

    If you assign a variable to clock interger with -format, you can use "-format %a%b..." to control the format, but next time, if you use the same grammer to set the variable, it will be replaced with some "??" characters in the variable.

    How can you fix it? just replace the "-format %a%b.." with "-format %%a%%b...", kind of weird. do you know why?

    package require Tk
    wm iconname . "New Interface"
    wm title . "Sales Query"
    wm minsize . 280 180

    set tmpmsg "..."
    set ed_date [clock format [clock seconds] -format "%Y-%m-%d"]
    set st_date [clock format [clock scan "-7 days" -base [clock second]] -format "%Y-%m-%d"]

    label .top01 -text "Sales Report" -padx 3 -fg "#5249f8" -font 16
    frame .fbody
    labelframe .fbody.fleft -text "Date Period" -padx 2 -pady 2
    frame .fbody.fleft.l1
    label .fbody.fleft.l1.lb1 -text "Start Date:" -anchor e -height 2 -width 12 -padx 3
    entry .fbody.fleft.l1.in1 -width 10 -textvariable st_date
    pack .fbody.fleft.l1.lb1 \
    .fbody.fleft.l1.in1 -side left -fill x -expand no

    frame .fbody.fleft.l2
    label .fbody.fleft.l2.lb1 -text "End Date:" -height 2 -anchor e -padx 3 -width 12
    entry .fbody.fleft.l2.in1 -width 10 -textvariable ed_date
    pack .fbody.fleft.l2.lb1 \
    .fbody.fleft.l2.in1 -side left -fill x -expand yes

    pack .fbody.fleft.l1 .fbody.fleft.l2 -side top -fill y

    labelframe .fbody.fright -text "Branch" -padx 2 -pady 2
    label .fbody.fright.lb1 -text "Next Left block" -height 2 -width 20 -padx 3 -relief sunk
    label .fbody.fright.lb2 -text "Next Right block" -height 2 -width 20 -padx 3 -relief sunk
    pack .fbody.fright.lb1 .fbody.fright.lb2 -side top -fill y -expand yes
    pack .fbody.fleft .fbody.fright -side left -padx 10 -pady 10 -expand yes

    label .mesg01 -textvariable tmpmsg

    frame .fbutton
    button .fbutton.bt01 -text "Reset" -relief raised
    button .fbutton.bt02 -text "Submit" -relief raised
    button .fbutton.bt03 -text "Quit" -relief raised
    pack .fbutton.bt01 .fbutton.bt02 .fbutton.bt03 \
    -side left -fill x -padx 5 -pady 3 -ipadx 2 -ipady 1 -expand yes
    bind .fbutton.bt03 "exit 0"
    bind .fbutton.bt02 {
    set tmpmsg "You Pressed me."
    #set st_date [clock format 111111111 -format "%%Y-%%m-%%d"]
    #set ed_date [clock format 111111111 -format "%%Y-%%m-%%d"]
    }

    bind .fbutton.bt01 {
    set st_date [clock format [clock scan "-1 day" -base [clock scan "$st_date"]] -format "%%Y-%%m-%%d" ]
    puts stdout [clock format [clock scan "-1 day" -base [clock second]] -format %%Y-%%m-%%d]
    .fbody.fright.lb1 configure -text [clock format [clock scan "-1 day" -base [clock second]] -format %%Y-%%m-%%d]
    set ed_date [clock format [clock scan "2 days" -base [clock scan "$ed_date"]] -format "%%Y-%%m-%%d"]
    set tmpmsg "[.fbody.fright.lb1 configure -text ]"
    flush stdout
    }

    pack .top01 .fbody .fbutton .mesg01 -side top -fill x -expand no

    ==There is another way you can make it. see here:

    cat timer
    #!/bin/sh
    # the next line restarts using wish \
    exec wish8.4 "$0" "$@"

    # timer --
    # This script generates a counter with start and stop buttons.
    #
    # RCS: @(#) $Id: timer,v 1.3 2001/10/29 16:23:33 dkf Exp $

    label .counter -text 0.00 -relief raised -width 10 -padx 2m -pady 1m
    button .start -text Start -command {
    if {$stopped} {
    set stopped 0
    set startMoment [clock clicks -milliseconds]
    #tick
    .stop configure -state normal
    .start configure -state disabled
    }
    }
    button .stop -text Stop -state disabled -command {
    set stopped 1
    .stop configure -state disabled
    .start configure -state normal
    }
    button .exit -text Exit -command {
    exit
    }
    pack .counter -side bottom -fill both
    pack .start -side left -fill both -expand yes
    pack .stop -side left -fill both -expand yes
    pack .exit -side right -fill both -expand yes

    set startMoment {}

    set stopped 1

    proc tick {} {
    global startMoment stopped fmttime fmtdate
    #set fmttime "%I:%M %P"
    set fmttime "%I:%M:%S %p"
    set fmtdate " %a %b %d, %Y "
    if {$stopped} {
    after 1000 tick
    .counter config -text [format "%s" [clock format [clock seconds] -format $fmttime]]
    # after 1000 tick
    return
    }
    after 50 tick
    set elapsedMS [expr {[clock clicks -milliseconds] - $startMoment}]
    .counter config -text [format "%.2f" [expr {double($elapsedMS)/1000}]]
    }

    bind . {destroy .}
    bind . {destroy .}
    focus .
    tick
  •  10-09-2009, 1:42 PM 11665 in reply to 8496

    Plotchart in Tcl/Tk Programming(1-2)

    Detail refer to http://docs.activestate.com/activetcl/8.5/tklib/plotchart/plotchart.html

    Description

    Plotchart is a Tcl-only package that focuses on the easy creation of xy-plots, barcharts and other common types of graphical presentations. The emphasis is on ease of use, rather than flexibility. The procedures that create a plot use the entire canvas window, making the layout of the plot completely automatic.

    This results in the creation of an xy-plot in, say, ten lines of code:

        package require Plotchart
    canvas .c -background white -width 400 -height 200
    pack .c -fill both
    #
    # Create the plot with its x- and y-axes
    #
    set s [::Plotchart::createXYPlot .c {0.0 100.0 10.0} {0.0 100.0 20.0}]
    foreach {x y} {0.0 32.0 10.0 50.0 25.0 60.0 78.0 11.0 } {
    $s plot series1 $x $y
    }
    $s title "Data series"

    A drawback of the package might be that it does not do any data management. So if the canvas that holds the plot is to be resized, the whole plot must be redrawn. The advantage, though, is that it offers a number of plot and chart types:

    • XY-plots like the one shown above with any number of data series.

    • Stripcharts, a kind of XY-plots where the horizontal axis is adjusted automatically. The result is a kind of sliding window on the data series.

    • Polar plots, where the coordinates are polar instead of cartesian.

    • Histograms, for plotting statistical information.

    • Isometric plots, where the scale of the coordinates in the two directions is always the same, i.e. a circle in world coordinates appears as a circle on the screen.

      You can zoom in and out, as well as pan with these plots (Note: this works best if no axes are drawn, the zooming and panning routines do not distinguish the axes), using the mouse buttons with the control key and the arrow keys with the control key.

    • Piecharts, with automatic scaling to indicate the proportions.

    • Barcharts, with either vertical or horizontal bars, stacked bars or bars side by side.

    • Timecharts, where bars indicate a time period and milestones or other important moments in time are represented by triangles.

    • 3D plots (both for displaying surfaces and 3D bars)

    With version 1.5 a new command has been introduced: plotconfig, which can be used to configure the plot options for particular types of plots and charts (cf. CONFIGURATION OPTIONS)

    PLOT CREATION COMMANDS

    You create the plot or chart with one single command and then fill the plot with data:

    ::Plotchart::createXYPlot w xaxis yaxis

    Create a new xy-plot (configuration type: xyplot).

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list xaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the x-axis, in this order. For an inverted axis, where the maximum appears on the left-hand side, use: maximum, minimum and a negative stepsize.

    list yaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the y-axis, in this order. For an inverted axis, where the maximum appears at the bottom, use: maximum, minimum and a negative stepsize.

    ::Plotchart::createStripchart w xaxis yaxis

    Create a new strip chart (configuration type: stripchart). The only difference to a regular XY plot is that the x-axis will be automatically adjusted when the x-coordinate of a new point exceeds the maximum.

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list xaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the x-axis, in this order. Note that an inverted x-axis is not supported for this type of plot.

    list yaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the y-axis, in this order. For an inverted axis, where the maximum appears at the bottom, use: maximum, minimum and a negative stepsize.

    ::Plotchart::createTXPlot w timeaxis xaxis

    Create a new time-x-plot (configuration type: txplot). The horizontal axis represents the date/time of the data and the vertical axis the values themselves.

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list timeaxis (in)

    A 3-element list containing the minimum and maximum date/time to be shown and the stepsize (in days) for the time-axis, in this order. Note that an inverted time-axis is not supported.

    list xaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the vertical axis, in this order. For an inverted axis, where the maximum appears at the bottom, use: maximum, minimum and a negative stepsize.

    ::Plotchart::createXLogYPlot w xaxis yaxis

    Create a new xy-plot where the y-axis has a logarithmic scale (configuration type: xlogyplot).

    The data should be given as for a linear scale, as the logarithmic transformation is taken of internally.

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list xaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the x-axis, in this order. For an inverted axis, where the maximum appears on the left-hand side, use: maximum, minimum and a negative stepsize.

    list yaxis (in)

    A 2-element list containing minimum and maximum for the y-axis, in this order. Note that an inverted logarithmic axis is not supported.

    ::Plotchart::createPolarPlot w radius_data

    Create a new polar plot (configuration type: polarplot).

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list radius_data (in)

    A 2-element list containing maximum radius and stepsize for the radial axis, in this order.

    ::Plotchart::createIsometricPlot w xaxis yaxis stepsize

    Create a new isometric plot, where the vertical and the horizontal coordinates are scaled so that a circle will truly appear as a circle (configuration type: isometric).

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list xaxis (in)

    A 2-element list containing minimum, and maximum for the x-axis, in this order.

    list yaxis (in)

    A 2-element list containing minimum, and maximum for the y-axis, in this order.

    float|noaxes stepsize (in)

    Either the stepsize used by both axes or the keyword noaxes to signal the plot that it should use the full area of the widget, to not draw any of the axes.

    ::Plotchart::createHistogram w xaxis yaxis

    Create a new histogram (configuration type: histogram).

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list xaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the x-axis, in this order.

    list yaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the y-axis, in this order.

    ::Plotchart::create3DPlot w xaxis yaxis zaxis

    Create a new 3D plot.

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list xaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the x-axis, in this order.

    list yaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the y-axis, in this order.

    list zaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the z-axis, in this order.

    ::Plotchart::createPiechart w

    Create a new piechart (configuration type: piechart).

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    ::Plotchart::createRadialchart w names scale style

    Create a new radial chart (the data are drawn as a line connecting the spokes of the diagram) (configuration type: radialchart).

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list names (in)

    Names for the spokes.

    float scale (in)

    Scale value to determine the position of the data along the spokes.

    float style (in)

    Style of the chart (optional). One of:

    • lines - the default: draw the data as independent polylines.

    • cumulative - draw the data as polylines where the data are accumulated.

    • filled - draw the data as filled polygons where the data are accumulated

    ::Plotchart::createBarchart w xlabels yaxis noseries

    Create a new barchart with vertical bars (configuration type: vertbars). The horizontal axis will display the labels contained in the argument xlabels. The number of series given by noseries determines both the width of the bars, and the way the series will be drawn.

    If the keyword stacked was specified the series will be drawn stacked on top of each other. Otherwise each series that is drawn will be drawn shifted to the right.

    The number of series determines the width of the bars, so that there is space of that number of bars. If you use a floating-point number, like 2.2, instead of an integer, like 2, a small gap between the sets of bars will be drawn - the width depends on the fractional part.

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list xlabels (in)

    List of labels for the x-axis. Its length also determines the number of bars that will be plotted per series.

    list yaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the y-axis, in this order.

    int|stacked noseries (in)

    The number of data series that will be plotted. This has to be an integer number greater than zero (if stacked is not used).

    ::Plotchart::createHorizontalBarchart w ylabels xaxis noseries

    Create a new barchart with horizontal bars (configuration type: horizbars). The vertical axis will display the labels contained in the argument ylabels. The number of series given by noseries determines both the width of the bars, and the way the series will be drawn.

    If the keyword stacked was specified the series will be drawn stacked from left to right. Otherwise each series that is drawn will be drawn shifted upward.

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list ylabels (in)

    List of labels for the y-axis. Its length also determines the number of bars that will be plotted per series.

    list xaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the x-axis, in this order.

    int|stacked noseries (in)

    The number of data series that will be plotted. This has to be an integer number greater than zero (if stacked is not used).

    ::Plotchart::create3DBarchart w yaxis nobars

    Create a new barchart with 3D vertical bars (configuration type: 3dbars). The horizontal axis will display the labels per bar. The number of bars given by nobarsdetermines the position and the width of the bars. The colours can be varied per bar. (This type of chart was inspired by the Wiki page on 3D bars by Richard Suchenwirth.)

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list yaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the y-axis, in this order.

    int nobars (in)

    The number of bars that will be plotted.

    ::Plotchart::create3DRibbonChart w names yaxis zaxis

    Create a new "ribbon chart" (configuration type: 3dribbon). This is a chart where the data series are represented as ribbons in a three-dimensional axis system. Along the x-axis (which is "into" the screen) the names are plotted, each representing a single series. The first plot command draws the furthest series, the second draws the series in front of that and so on.

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    widget w (in)

    Names of the series, plotted as labels along the x-axis

    list yaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the y-axis (drawn horizontally!), in this order.

    list zaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the z-axis (drawn vertically), in this order.

    int nobars (in)

    The number of bars that will be plotted.

    ::Plotchart::createBoxplot w xaxis ylabels

    Create a new boxplot with horizontal boxes (box-and-whiskers). The y-axis is drawn with labels. The boxes are drawn based on the raw data (see the plot subcommand for this type of plot).

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list xaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the y-axis, in this order.

    list ylabels (in)

    List of labels for the y-axis. Its length also determines the number of boxes that can be plotted. The labels are also used in the plot subcommand.

    ::Plotchart::createTimechart w time_begin time_end args

    Create a new timechart (configuration type: timechart). The time axis (= x-axis) goes from time_begin to time_end, and the vertical spacing is determined by the number of items to plot.

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    string time_begin (in)

    The start time given in a form that is recognised by the clock scan command (e.g. "1 january 2004").

    string time_end (in)

    The end time given in a form that is recognised by the clock scan command (e.g. "1 january 2004").

    arguments args (in)

    The remaining arguments can be:

    • The expected/maximum number of items. This determines the vertical spacing. (If given, it must be the first argument after "time_end"

    • The keyword -barheight and the number of pixels per bar. This is an alternative method to determine the vertical spacing.

    • The keyword -ylabelwidth and the number of pixels to reserve for the labels at the y-axis.

    ::Plotchart::createGanttchart w time_begin time_end args

    Create a new Gantt chart (configuration type: ganttchart). The time axis (= x-axis) goes from time_begin to time_end, and the vertical spacing is determined by the number of items to plot. Via the specific commands you can then add tasks and connections between the tasks.

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    string time_begin (in)

    The start time given in a form that is recognised by the clock scan command (e.g. "1 january 2004").

    string time_end (in)

    The end time given in a form that is recognised by the clock scan command (e.g. "1 january 2004").

    arguments args (in)

    The remaining arguments can be:

    • The expected/maximum number of items. This determines the vertical spacing. (If given this way, it must be the first argument after "time_end")

    • The expected/maximum width of the descriptive text (roughly in characters, for the actual space reserved for the text, it is assumed that a character is about ten pixels wide). Defaults to 20. (If given this way, it must be the second argument after "time_end").

    • The keyword -barheight and the number of pixels per bar. This is an alternative method to determine the vertical spacing.

    • The keyword -ylabelwidth and the number of pixels to reserve for the labels at the y-axis.

    ::Plotchart::createRightAxis w yaxis

    Create a plot command that will use a right axis instead of the left axis (configuration type: inherited from the existing plot). The widget (w) must already contain an ordinary plot, as the horizontal axis and other properties are reused. To plot data using the right axis, use this new command, to plot data using the left axis, use the original plot command.

    widget w (in)

    Name of the existing canvas widget to hold the plot.

    list yaxis (in)

    A 3-element list containing minimum, maximum and stepsize for the y-axis, in this order.

    PLOT METHODS

    Each of the creation commands explained in the last section returns the name of a new object command that can be used to manipulate the plot or chart. The subcommands available to a chart command depend on the type of the chart.

    General subcommands for all types of charts. $anyplot is the command returned by the creation command:

    $anyplot title text

    Specify the title of the whole chart.

    string text (in)

    The text of the title to be drawn.

    $anyplot saveplot filename args

    Draws the plot into a file, using PostScript.

    string filename (in)

    Contain the path name of the file to write the plot to.

    list args (in)

    Optionally you can specify the option -format "some picture format" to store the plot in a different file than a PostScript file. This, however, relies on the Img package to do the actual job.

    Note: Because the window holding the plot must be fully visible before Img can successfully grab it, it is raised first. On some systems, for instance Linux with KDE, raising a window is not done automatically, but instead you need to click on the window in the task bar. Similar things happen on Windows XP.

    There seems to be something wrong under some circumstances, so instead of waiting for the visibility of the window, the procedure simply waits two seconds. It is not ideal, but it seems to work better.

    $anyplot xtext text

    Specify the title of the (horizontal) x-axis, for those plots that have a straight x-axis.

    string text (in)

    The text of the x-axis label to be drawn.

    $anyplot ytext text

    Specify the title of the (horizontal) y-axis, for those plots that have a straight y-axis.

    string text (in)

    The text of the y-axis label to be drawn.

    $anyplot xconfig -option value ...

    Set one or more configuration parameters for the x-axis. The following options are supported:

    format fmt

    The format for the numbers along the axis.

    ticklength length

    The length of the tickmarks (in pixels).

    ticklines boolean

    Whether to draw ticklines (true) or not (false).

    scale scale_data

    New scale data for the axis, i.e. a 3-element list containing minimum, maximum and stepsize for the axis, in this order.

    Beware: Setting this option will clear all data from the plot.

    $anyplot yconfig -option value ...

    Set one or more configuration parameters for the y-axis. This method accepts the same options and values as the method xconfig.

    $anyplot background part colour_or_image dir

    Set the background of a part of the plot

    string part

    Which part of the plot: "axes" for the axes area and "plot" for the inner part. The interpretation depends on the type of plot. Two further possibilities are:

    • image, in which case a predefined image is loaded into the background of the plot.

    • gradient, in which case the background is coloured in different shades of the given colour. The "dir" argument specifies the direction in which the colour gets whiter.

    string colour_or_image

    Colour for that part or the name of the image if "part" is "image"

    string dir

    The direction of the gradient. One of: top-down, bottom-up, left-right or right-left.

    $anyplot xticklines colour

    Draw vertical ticklines at each tick location

    string colour

    Colour of the lines. Specifying an empty colour ("") removes them again. Defaults to "black"

    $anyplot yticklines colour

    Draw horizontal ticklines at each tick location

    string colour

    Colour of the lines. Specifying an empty colour ("") removes them again Defaults to "black"

    $anyplot legendconfig -option value ...

    Set one or more options for the legend. The legend is drawn as a rectangle with text and graphics inside.

    background colour

    Set the colour of the background (the default colour is white). Set to the empty string for a transparant legend.

    border colour

    Set the colour of the border (the default colour is white). Set to the empty string if you do not want a border.

    canvas c

    Draw the legend in a different canvas widget. This gives you the freedom to position the legend outside the actual plot.

    position corner

    Set the position of the legend. May be one of: top-left, top-right, bottom-left or bottom-right. (Default value is top-right.)

    $anyplot legend series text

    Add an entry to the legend. The series determines which graphical symbol is to be used. (As a side effect the legend is actually drawn.)

    string series

    Name of the data series. This determines the colour of the line and the symbol (if any) that will be drawn.

    string text

    Text to be drawn next to the line/symbol.

    $anyplot balloon x y text dir

    Add balloon text to the plot (except for 3D plots). The arrow will point to the given x- and y-coordinates. For xy-graphs and such, the coordinates are directly related to the axes; for vertical barcharts the x-coordinate is measured as the number of bars minus 1 and similar for horizontal barcharts.

    float x

    X-coordinate of the point that the arrow of the balloon will point to.

    float y

    Y-coordinate of the point that the arrow of the balloon will point to.

    string text

    Text to be drawn in the balloon.

    string dir

    Direction of the arrow, one of: north, north-east, east, south-east, south, south-west, west or north-west.

    $anyplot balloonconfig args

    Configure the balloon text for the plot. The new settings will be used for the next balloon text.

    font fontname

    Font to be used for the text

    justify left|center|right

    Way to justify multiline text

    textcolour colour

    Colour for the text (synonym: textcolor)

    background colour

    Background colour for the balloon

    outline colour

    Colour of the outline of the balloon

    margin value

    Margin around the text (in pixels)

    rimwidth value

    Width of the outline of the balloon (in pixels)

    arrowsize value

    Length factor for the arrow (in pixels)

    Note: The commands xconfig and yconfig are currently implemented only for XY-plots and only the option -format has any effect.

    For xy plots, stripcharts, histograms and time-x-plots:

    $xyplot plot series xcrd ycrd

    Add a data point to the plot.

    string series (in)

    Name of the data series the new point belongs to.

    float xcrd (in)

    X-coordinate of the new point. (For time-x plots this must be valid date/time that can be read with the clock scan command).

    float ycrd (in)

    Y-coordinate of the new point.

    Note on histograms:

    For histograms the x-coordinate that is given is interpreted to be the x-coordinate of the right side of the bar. The first bar starts at the y-axis on the left. To completely fill the range of the x-axis, you should draw a bar at the maximum x-coordinate.

    For xy plots:

    $xyplot trend series xcrd ycrd

    Draw or update a trend line using the data given sofar.

    string series (in)

    Name of the data series the trend line belongs to.

    float xcrd (in)

    X-coordinate of the new data point

    float ycrd (in)

    Y-coordinate of the new data point

    $xyplot rchart series xcrd ycrd

    Draw data in the same way as the plot method, but with two lines added that indicate the expected range (+/- 3*standard deviation) of the data.

    string series (in)

    Name of the data series the data point belongs to.

    float xcrd (in)

    X-coordinate of the new data point

    float ycrd (in)

    Y-coordinate of the new data point

    $xyplot interval series xcrd ymin ymax ?ycentr?

    Add a vertical error interval to the plot. The interval is drawn from ymin to ymax. If the ycentr argument is given, a symbol is drawn at that position.

    string series (in)

    Name of the data series the interval belongs to.

    float xcrd (in)

    X-coordinate of the interval

    float ymin (in)

    Minimum y-coordinate of the interval.

    float ymax (in)

    Maximum y-coordinate of the interval.

    float ycentr (in)

    Y-coordinate to draw the symbol at (optional)

    $xyplot box-and-whiskers series xcrd ycrd

    Draw a box and whiskers in the plot. If the argument xcrd is a list of several values and the argument ycrd is a single value, a horizontal box is drawn with the quartiles determined from the list of values contained in xcrd.

    If, instead, the argument ycrd contains a list of several values and the argument xcrd a single value, then a vertical box is drawn and the quartiles are determined fromycrd. (There must be exactly one list of several values. Otherwise an error is reported.)

    The option -boxwidth (default: 10 pixels) determines the width (or height) of the box.

    string series (in)

    Name of the data series the box-and-whiskers belongs to.

    float xcrd (in)

    X-coordinate of the box or a list of values.

    float ymin (in)

    Y-coordinate of the box or a list of values.

    $xyplot vector series xcrd ycrd ucmp vcmp

    Draw a vector in the plot. The vector can be given as either cartesian coordinates or as length/angle, where the angle is in degrees and is interpreted according to the mathematical convention or the nautical. (See the vectorconfig subcommand)

    string series (in)

    Name of the series the vector belongs to. Determines the appearance and interpretation.

    float xcrd (in)

    X-coordinate of the point where the arrow appears

    float ycrd (in)

    Y-coordinate of the point where the arrow appears

    float ucmp (in)

    X-component or the length of the vector

    float ycentr (in)

    Y-component or the angle of the vector

    $xyplot vectorconfig series -option value ...

    ] Set the vector drawing options for a particular series

    string series (in)

    Name of the series the vector belongs to.

    The options can be one of the following:

    colour

    The colour of the arrow (default: black; synonym: color)

    scale value

    The scale factor used to convert the length of the arrow into a number of pixels (default: 1.0)

    centred onoff

    Logical value indicating that the xy-coordinates are to be used as the start of the arrow or as the centre (default: 0; synonym: centered)

    type keyword

    Interpretation of the vector components. Can be "cartesian" (default), in which case the x- and y-components are expected, "polar" (the angle 0 coincides with the positive x-axis, 90 coincides with the positive y-axis) or "nautical" (0 is "north" and 90 is "east").

  •  10-09-2009, 1:44 PM 11666 in reply to 11665

    Plotchart in Tcl/Tk Programming(2-2)

    $xyplot dot series xcrd ycrd value

    Draw a dot in the plot. The size and colour is determined by the value and by the options set for the series it belongs to. (See the dotconfig subcommand)

    string series (in)

    Name of the series the dot belongs to. Determines size and colour

    float xcrd (in)

    X-coordinate of the point where the arrow appears

    float ycrd (in)

    Y-coordinate of the point where the arrow appears

    float value (in)

    Value determining size and colour

    $xyplot dotconfig series -option value ...

    ] Set the dot drawing options for a particular series

    string series (in)

    Name of the series the dot belongs to.

    The options can be one of the following:

    colour

    The colour of the dot if no scaling is used or the value exceeds the last limit of the classes.

    scale value

    The scale factor used to convert the value into the radius of the dot in pixels (default: 1.0)

    radius value

    The default radius of the dots, used if there is no scaling by value (in pixels; default: 3)

    scalebyvalue onoff

    Determines whether the dots all have the same size or a size depending on the given value (default: on).

    outline onoff

    Draw a black circle around the dot or not (default: on)

    classes list

    Set the limits and the corresponding colours. For instance:

        $xyplot series1 -classes {0 blue 1 green} -colour red

    will cause a blue dot to be drawn for values smaller than 0, a green dot for values larger/equal 0 but lower than 1 and a red dot for values larger/equal 1.

    If there is no list of classes for the particular series, the dots are scaled by the value.

    You can combine the colouring by value and the scaling by value by setting a list of classes and setting the scalebyvalue option on.

    $xyplot contourlines xcrd ycrd values ?classes?

    Draw contour lines for the values given on the grid. The grid is defined by the xcrd and ycrd arguments (they give the x- and y-coordinates of the grid cell corners). The values are given at these corners. The classes determine which contour lines are drawn. If a value on one of the corners is missing, the contour lines in that cell will not be drawn.

    list xcrd (in)

    List of lists, each value is an x-coordinate for a grid cell corner

    list ycrd (in)

    List of lists, each value is an y-coordinate for a grid cell corner

    list values (in)

    List of lists, each value is the value at a grid cell corner

    list classes (in)

    List of class values or a list of lists of two elements (each inner list the class value and the colour to be used). If empty or missing, the classes are determined automatically.

    Note: The class values must enclose the whole range of values.

    $xyplot contourfill xcrd ycrd values ?classes?

    Draw filled contours for the values given on the grid. (The use of this method is identical to the "contourlines" method).

    $xyplot contourbox xcrd ycrd values ?classes?

    Draw the cells as filled quadrangles. The colour is determined from the average of the values on all four corners.

    $xyplot colorMap colours

    Set the colours to be used with the contour methods. The argument is either a predefined colourmap (grey/gray, jet, hot or cool) or a list of colours. When selecting the colours for actually drawing the contours, the given colours will be interpolated (based on the HLS scheme).

    list colours (in)

    List of colour names or colour values or one of the predefined maps:

    • grey or gray: gray colours from dark to light

    • jet: rainbow colours

    • hot: colours from yellow via red to darkred

    • cool: colours from cyan via blue to magenta

    $xyplot grid xcrd ycrd

    Draw the grid cells as lines connecting the (valid) grid points.

    list xcrd (in)

    List of lists, each value is an x-coordinate for a grid cell corner

    list ycrd (in)

    List of lists, each value is an y-coordinate for a grid cell corner

    For polar plots:

    $polarplot plot series radius angle

    Add a data point to the polar plot.

    string series (in)

    Name of the data series the new point belongs to.

    float radius (in)

    Radial coordinate of the new point.

    float angle (in)

    Angular coordinate of the new point (in degrees).

    For 3D plots:

    $plot3d plotfunc function

    Plot a function defined over two variables x and y. The resolution is determined by the set grid sizes (see the method gridsize for more information).

    string function (in)

    Name of the procedure that calculates the z-value for the given x and y coordinates. The procedure has to accept two float arguments (x is first argument, y is second) and return a floating-point value.

    $plot3d plotfuncont function contours

    Plot a function defined over two variables x and y using the contour levels in contours to colour the surface. The resolution is determined by the set grid sizes (see the method gridsize for more information).

    string function (in)

    Name of the procedure that calculates the z-value for the given x and y coordinates. The procedure has to accept two float arguments (x is first argument, y is second) and return a floating-point value.

    list contours (in)

    List of values in ascending order that represent the contour levels (the boundaries between the colours in the contour map).

    $plot3d gridsize nxcells nycells

    Set the grid size in the two directions. Together they determine how many polygons will be drawn for a function plot.

    int nxcells (in)

    Number of grid cells in x direction. Has to be an integer number greater than zero.

    int nycells (in)

    Number of grid cells in y direction. Has to be an integer number greater than zero.

    $plot3d plotdata data

    Plot a matrix of data.

    list data (in)

    The data to be plotted. The data has to be provided as a nested list with 2 levels. The outer list contains rows, drawn in y-direction, and each row is a list whose elements are drawn in x-direction, for the columns. Example:

        set data {
    {1.0 2.0 3.0}
    {4.0 5.0 6.0}
    }
    $plot3d colours fill border

    Configure the colours to use for polygon borders and inner area.

    color fill (in)

    The colour to use for filling the polygons.

    color border (in)

    The colour to use for the border of the polygons.

    For xy plots, stripcharts and polar plots:

    $xyplot dataconfig series -option value ...

    Set the value for one or more options regarding the drawing of data of a specific series.

    string series (in)

    Name of the data series whose configuration we are changing.

    The following options are allowed:

    colour ccolor c

    The colour to be used when drawing the data series.

    type enum

    The drawing mode chosen for the series. This can be one of line, symbol, or both.

    symbol enum

    What kind of symbol to draw. The value of this option is ignored when the drawing mode line was chosen. This can be one of plus, cross, circle, up (triangle pointing up), down (triangle pointing down), dot (filled circle), upfilled or downfilled (filled triangles).

    filled enum

    Whether to fill the area above or below the data line or not. Can be one of: no, up or down (SPECIAL EFFECTS)

    fillcolour colour

    Colour to use when filling the area associated with the data line.

    For piecharts:

    $pie plot data

    Fill a piechart.

    list data (in)

    A list of pairs (labels and values). The values determine the relative size of the circle segments. The labels are drawn beside the circle.

    $pie colours colour1 colour2 ...

    Set the colours to be used.

    color colour1 (in)

    The first colour.

    color colour2 (in)

    The second colour, and so on.

    For radial charts:

    $radial plot data colour thickness

    Draw a new line in the radial chart

    list data (in)

    A list of data (one for each spoke). The values determine the distance from the centre of the line connecting the spokes.

    color colour (in)

    The colour for the line.

    int thickness (in)

    An optional argument for the thickness of the line.

    $pie colours colour1 colour2 ...

    Set the colours to be used.

    color colour1 (in)

    The first colour.

    color colour2 (in)

    The second colour, and so on.

    For vertical barcharts:

    $barchart plot series ydata colour

    Add a data series to a barchart.

    string series (in)

    Name of the series the values belong to.

    list ydata (in)

    A list of values, one for each x-axis label.

    color colour (in)

    The colour of the bars.

    For horizontal barcharts:

    $barchart plot series xdata colour

    Add a data series to a barchart.

    string series (in)

    Name of the series the values belong to.

    list xdata (in)

    A list of values, one for each y-axis label.

    color colour (in)

    The colour of the bars.

    For 3D barcharts:

    $barchart plot label yvalue colour

    Add the next bar to the barchart.

    string label (in)

    The label to be shown below the column.

    float yvalue (in)

    The value that determines the height of the column

    color colour (in)

    The colour of the column.

    $barchart config -option value ...

    Set one or more configuration parameters. The following options are supported:

    usebackground boolean

    Whether to draw walls to the left and to the back of the columns or not

    useticklines boolean

    Whether to draw ticklines on the walls or not

    showvalues boolean

    Whether to show the values or not

    labelfont newfont

    Name of the font to use for labels

    labelcolour colour

    Colour for the labels

    valuefont newfont

    Name of the font to use for the values

    valuecolour colour

    Colour for the values

    For 3D ribbon charts:

    $ribbon line xypairs colour

    Plot the given xy-pairs as a ribbon in the chart

    list xypairs (in)

    The pairs of x/y values to be drawn (the series is drawn as a whole)

    color colour (in)

    The colour of the ribbon.

    $ribbon area xypairs colour

    Plot the given xy-pairs as a ribbon with a filled area in front. The effect is that of a box with the data as its upper surface.

    list xypairs (in)

    The pairs of x/y values to be drawn (the series is drawn as a whole)

    color colour (in)

    The colour of the ribbon/area.

    For boxplots:

    $boxplot plot label values

    Add a box-and-whisker to the plot.

    string label (in)

    The label along the y-axis to which the data belong

    list values (in)

    List of raw values, the extent of the box and the whiskers will be determined from this list.

    For timecharts:

    $timechart period text time_begin time_end colour

    Add a time period to the chart.

    string text (in)

    The text describing the period.

    string time_begin (in)

    Start time of the period.

    string time_end (in)

    Stop time of the period.

    color colour (in)

    The colour of the bar (defaults to black).

    $timechart milestone text time colour

    Add a milestone (represented as an point-down triangle) to the chart.

    string text (in)

    The text describing the milestone.

    string time (in)

    Time at which the milestone must be positioned.

    color colour (in)

    The colour of the triangle (defaults to black).

    $timechart vertline text time

    Add a vertical line (to indicate the start of the month for instance) to the chart.

    string text (in)

    The text appearing at the top (an abbreviation of the date/time for instance).

    string time (in)

    Time at which the line must be positioned.

    $timechart hscroll scrollbar

    Connect a horizontal scrollbar to the chart. See also the section on scrolling.

    widget scrollbar (in)

    The horizontal scrollbar that is to be connected to the chart

    $timechart vscroll scrollbar

    Connect a vertical scrollbar to the chart. See also the section on scrolling.

    widget scrollbar (in)

    The vertical scrollbar that is to be connected to the chart

    For Gantt charts:

    $ganttchart task text time_begin time_end completed

    Add a task with its period and level of completion to the chart. Returns a list of canvas items that can be used for further manipulations, like connecting two tasks.

    string text (in)

    The text describing the task.

    string time_begin (in)

    Start time of the task.

    string time_end (in)

    Stop time of the task.

    float completed (in)

    The percentage of the task that is completed.

    $ganttchart milestone text time colour

    Add a milestone (represented as an point-down triangle) to the chart.

    string text (in)

    The text describing the milestone.

    string time (in)

    Time at which the milestone must be positioned.

    color colour (in)

    The colour of the triangle (defaults to black).

    $ganttchart vertline text time

    Add a vertical line (to indicate the start of the month for instance) to the chart.

    string text (in)

    The text appearing at the top (an abbreviation of the date/time for instance).

    string time (in)

    Time at which the line must be positioned.

    $ganttchart connect from to

    Add an arrow that connects the from task with the to task.

    list from (in)

    The list of items returned by the "task" command that represents the task from which the arrow starts.

    string text (in)

    The text summarising the tasks

    list args (in)

    One or more tasks (the lists returned by the "task" command). They are shifted down to make room for the summary.

    list to (in)

    The list of items returned by the "task" command that represents the task at which the arrow ends.

    $ganttchart summary text args

    Add a summary item that spans all the tasks listed. The graphical representation is a thick bar running from the leftmost task to the rightmost.

    Use this command before connecting the tasks, as the arrow would not be shifted down!

    string text (in)

    The text summarising the tasks

    list args (in)

    One or more tasks (the lists returned by the "task" command). They are shifted down to make room for the summary.

    $ganttchart color keyword newcolor

    Set the colour of a part of the Gantt chart. These colours hold for all items of that type.

    string keyword (in)

    The keyword indicates which part of the Gantt chart to change:

    • description - the colour of the descriptive text

    • completed - the colour of the filled bar representing the completed part of a task

    • left - the colour for the part that is not yet completed

    • odd - the background colour for the odd entries

    • even - the background colour for the even entries

    • summary - the colour for the summary text

    • summarybar - the colour for the bar for a summary

    string newcolor (in)

    The new colour for the chosen items.

    $ganttchart font keyword newfont

    Set the font of a part of the Gantt chart. These fonts hold for all items of that type.

    string keyword (in)

    The keyword indicates which part of the Gantt chart to change:

    • description - the font used for descriptive text

    • summary - the font used for summaries

    • scale - the font used for the time scale

    string newfont (in)

    The new font for the chosen items.

    $ganttchart hscroll scrollbar

    Connect a horizontal scrollbar to the chart. See also the section on scrolling.

    widget scrollbar (in)

    The horizontal scrollbar that is to be connected to the chart

    $ganttchart vscroll scrollbar

    Connect a vertical scrollbar to the chart. See also the section on scrolling.

    widget scrollbar (in)

    The vertical scrollbar that is to be connected to the chart

    For isometric plots (to be extended):

    $isoplot plot rectangle x1 y1 x2 y2 colour

    Plot the outlines of a rectangle.

    float x1 (in)

    Minimum x coordinate of the rectangle to be drawn.

    float y1 (in)

    Minimum y coordinate of the rectangle.

    float x2 (in)

    Maximum x coordinate of the rectangle to be drawn.

    float y2 (in)

    Maximum y coordinate of the rectangle.

    color colour (in)

    The colour of the rectangle.

    $isoplot plot filled-rectangle x1 y1 x2 y2 colour

    Plot a rectangle filled with the given colour.

    float x1 (in)

    Minimum x coordinate of the rectangle to be drawn.

    float y1 (in)

    Minimum y coordinate of the rectangle.

    float x2 (in)

    Maximum x coordinate of the rectangle to be drawn.

    float y2 (in)

    Maximum y coordinate of the rectangle.

    color colour (in)

    The colour of the rectangle.

    $isoplot plot circle xc yc radius colour

    Plot the outline of a circle.

    float xc (in)

    X coordinate of the circle's centre.

    float yc (in)

    Y coordinate of the circle's centre.

    color colour (in)

    The colour of the circle.

    $isoplot plot filled-circle xc yc radius colour

    Plot a circle filled with the given colour.

    float xc (in)

    X coordinate of the circle's centre.

    float yc (in)

    Y coordinate of the circle's centre.

    color colour (in)

    The colour of the circle.

    There are a number of public procedures that may be useful in specific situations: Pro memorie.

    COORDINATE TRANSFORMATIONS

    Besides the commands that deal with the plots and charts directly, there are a number of commands that can be used to convert world coordinates to pixels and vice versa. These include:

    ::Plotchart::viewPort w pxmin pymin pxmax pymax

    Set the viewport for window w. Should be used in cooperation with ::Plotchart::worldCoordinates.

    widget w (in)

    Name of the window (canvas widget) in question.

    float pxmin (in)

    Left-most pixel coordinate.

    float pymin (in)

    Top-most pixel coordinate (remember: the vertical pixel coordinate starts with 0 at the top!).

    float pxmax (in)

    Right-most pixel coordinate.

    float pymax (in)

    Bottom-most pixel coordinate.

    ::Plotchart::worldCoordinates w xmin ymin xmax ymax

    Set the extreme world coordinates for window w. The world coordinates need not be in ascending order (i.e. xmin can be larger than xmax, so that a reversal of the x-axis is achieved).

    widget w (in)

    Name of the window (canvas widget) in question.

    float xmin (in)

    X-coordinate to be mapped to left side of viewport.

    float ymin (in)

    Y-coordinate to be mapped to bottom of viewport.

    float xmax (in)

    X-coordinate to be mapped to right side of viewport.

    float ymax (in)

    Y-coordinate to be mapped to top side of viewport.

    ::Plotchart::world3DCoordinates w xmin ymin zmin xmax ymax zmax

    Set the extreme three-dimensional world coordinates for window w. The world coordinates need not be in ascending order (i.e. xmin can be larger than xmax, so that a reversal of the x-axis is achieved).

    widget w (in)

    Name of the window (canvas widget) in question.

    float xmin (in)

    X-coordinate to be mapped to front side of the 3D viewport.

    float ymin (in)

    Y-coordinate to be mapped to left side of the viewport.

    float zmin (in)

    Z-coordinate to be mapped to bottom of viewport.

    float xmax (in)

    X-coordinate to be mapped to back side of viewport.

    float ymax (in)

    Y-coordinate to be mapped to right side of viewport.

    float zmax (in)

    Z-coordinate to be mapped to top side of viewport.

    ::Plotchart::coordsToPixel w x y

    Return a list of pixel coordinates valid for the given window.

    widget w (in)

    Name of the window (canvas widget) in question.

    float x (in)

    X-coordinate to be mapped.

    float y (in)

    Y-coordinate to be mapped.

    ::Plotchart::coords3DToPixel w x y z

    Return a list of pixel coordinates valid for the given window.

    widget w (in)

    Name of the window (canvas widget) in question.

    float x (in)

    X-coordinate to be mapped.

    float y (in)

    Y-coordinate to be mapped.

    float y (in)

    Z-coordinate to be mapped.

    ::Plotchart::polarCoordinates w radmax

    Set the extreme polar coordinates for window w. The angle always runs from 0 to 360 degrees and the radius starts at 0. Hence you only need to give the maximum radius. Note: If the viewport is not square, this procedure will not adjust the extremes, so that would result in an elliptical plot. The creation routine for a polar plot always determines a square viewport.

    widget w (in)

    Name of the window (canvas widget) in question.

    float radmax (in)

    Maximum radius.

    ::Plotchart::polarToPixel w rad phi

    Wrapper for a call to ::Plotchart::coordsToPixel, which assumes the world coordinates and viewport are set appropriately. Converts polar coordinates to pixel coordinates. Note: To be useful it should be accompanied by a matching ::Plotchart::worldCoordinates procedure. This is automatically taken care of in the creation routine for polar plots.

    widget w (in)

    Name of the window (canvas widget) in question.

    float rad (in)

    Radius of the point.

    float phi (in)

    Angle to the positive x-axis.

    ::Plotchart::pixelToCoords w x y

    Return a list of world coordinates valid for the given window.

    widget w (in)

    Name of the window (canvas widget) in question.

    float x (in)

    X-pixel to be mapped.

    float y (in)

    Y-pixel to be mapped.

    ::Plotchart::pixelToIndex w x y

    Return the index of the pie segment containing the pixel coordinates (x,y)

    widget w (in)

    Name of the window (canvas widget) in question, holding a piechart.

    float x (in)

    X-pixel to be mapped.

    float y (in)

    Y-pixel to be mapped.

    Furthermore there is a routine to determine "pretty" numbers for use with an axis:

    ::Plotchart::determineScale xmin xmax inverted

    Determine "pretty" numbers from the given range and return a list containing the minimum, maximum and stepsize that can be used for a (linear) axis.

    float xmin (in)

    Rough minimum value for the scaling

    float xmax (in)

    Rough maximum value for the scaling.

    boolean inverted (in)

    Optional argument: if 1, then the returned list produces an inverted axis. Defaults to 0 (the axis will be from minimum to maximum)

    MISSING VALUES

    Often data that need to be plotted contain gaps - in a series of measurement data, they can occur because the equipment failed, a sample was not collected correctly or for many other reasons. The Plotchart handles these gaps by assuming that one or both coordinates of such data points are an empty string:

        #
    # Create the plot with its x- and y-axes
    #
    set s [::Plotchart::createXYPlot .c {0.0 100.0 10.0} {0.0 100.0 20.0}]
    foreach {x y} {0.0 32.0 10.0 {} 25.0 60.0 78.0 11.0 } {
    $s plot series1 $x $y
    }

    The effect varies according to the type of plot:

    • For xy-plots, radial plots and strip charts the missing data point causes a gap in the line through the points.

    • For barchats, missing values are treated as if a value of zero was given.

    • For time charts and Gantt charts missing values cause errors - there is no use for them there.

    OTHER OUTPUT FORMATS

    Besides output to the canvas on screen, the module is capable, via canvas postscript, of producing PostScript files. One may wonder whether it is possible to extend this set of output formats and the answer is "yes". This section tries to sum up the aspects of using this module for another sort of output.

    One way you can create output files in a different format, is by examining the contents of the canvas after everything has been drawn and render that contents in the right form. This is probably the easiest way, as it involves nothing more than the re-creation of all the elements in the plot that are already there.

    The drawback of that method is that you need to have a display, which is not always the case if you run a CGI server or something like that.

    An alternative is to emulate the canvas command. For this to work, you need to know which canvas subcommands are used and what for. Obviously, the create subcommand is used to create the lines, texts and other items. But also the raise and lower subcommands are used, because with these the module can influence the drawing order - important to simulate a clipping rectangle around the axes. (The routine DrawMask is responsible for this - if the output format supports proper clipping areas, then a redefinition of this routine might just solve this).

    Furthermore, the module uses the cget subcommand to find out the sizes of the canvas. A more mundane aspect of this is that the module currently assumes that the text is 14 pixels high and that 80 pixels in width suffice for the axis' labels. No "hook" is provided to customise this.

    In summary:

    • Emulate the create subcommand to create all the items in the correct format

    • Emulate the cget subcommand for the options -width and -height to allow the correct calculation of the rectangle's position and size

    • Solve the problem of raising and lowering the items so that they are properly clipped, for instance by redefining the routine DrawMask.

    • Take care of the currently fixed text size properties

    SPECIAL EFFECTS

    As an example of some special effects you can achieve, here is the code for a plot where the area below the data line varies in colour:

    canvas .c  -background white -width 400 -height 200
    pack .c -fill both
    set s [::Plotchart::createXYPlot .c {0.0 100.0 10.0} {0.0 100.0 20.0}]
    $s background gradient green top-down
    $s dataconfig series1 -filled up -fillcolour white
    $s plot series1 0.0 20.0
    $s plot series1 10.0 20.0
    $s plot series1 30.0 50.0
    $s plot series1 35.0 45.0
    $s plot series1 45.0 25.0
    $s plot series1 75.0 55.0
    $s plot series1 100.0 55.0
    $s plaintext 30.0 60.0 "Peak" south

    The trick is to fill the background with a colour that changes from green at the top to white at the bottom. Then the area above the data line is filled with a white polygon. Thus the green shading varies with the height of the line.

    ROOM FOR IMPROVEMENT

    In this version there are a lot of things that still need to be implemented:

    • More robust handling of incorrect calls (right now the procedures may fail when called incorrectly):

      • The axis drawing routines can not handle inverse axes right now.

      • If the user provides an invalid date/time string, the routines simply throw an error.

    RESIZING

    Plotchart has not been designed to create plots and charts that keep track of the data that are put in. This means that if an application needs to allow the user to resize the window holding the plot or chart, it must take care to redraw the complete plot.

    The code below is a simple example of how to do that:

    package require Plotchart
    grid [canvas .c -background white] -sticky news
    grid columnconfigure . 0 -weight 1
    grid rowconfigure . 0 -weight 1
    bind .c <Configure> {doResize}
    proc doPlot {} {
    #
    # Clean up the contents (see also the note below!)
    #
    .c delete all
    #
    # (Re)draw the bar chart
    #
    set p [::Plotchart::createBarchart .c {x y z} {0 100 10} 3]
    $p plot R {10 30 40} red
    $p plot G {30 40 60} green
    }
    proc doResize {} {
    global redo
    #
    # To avoid redrawing the plot many times during resizing,
    # cancel the callback, until the last one is left.
    #
    if { [info exists redo] } {
    after cancel $redo
    }
    set redo [after 50 doPlot]
    }

    Please note: The code above will work fine for barcharts and many other types of plots, but as Plotchart keeps some private information for xy plots, more is needed in these cases. This actually requires a command "destroyPlot" to take care of such details. A next version of Plotchart will have that.

    ZOOMING IN

    As the Plotchart package does not keep track of the data itself, rescaling an existing plot - for instance when zooming in - would have to be done by redefining the plot and redrawing the data. However, the canvas widget offers a way out by scaling and moving items, so that zooming in becomes a bit simpler.

    Whether zooming is indeed useful, depends on the type of plot. Currently it is defined for XY-plots only. The method is called "rescale" and simply redraws the axes and scales and moves the data items so that they conform to the new axes. The drawback is that any symbols are scaled by the same amount. The rescale method works best for plots that only have lines, not symbols.

    The method works very simply:

       $p rescale {newxmin newxmax newxstep} {newymin newymax newystep}

    CONFIGURATION OPTIONS

    The command plotconfig can be used to set all manner of options. The syntax is:

    ::Plotchart::plotconfig charttype component property value

    Set a new value for the property of a component in a particular chart or plot type or query its current value. Each argument is optional.

    string charttype (in)

    The type of chart or plot (see the configuration type that is mentioned for each create command). If not given or empty, a list of chart types is returned. If it is given, the properties for that particular type are used.

    string component (in)

    The component of the plot/chart: leftaxis, rightaxis, background, margin and so on. If not given or empty, a list of components is returned. If it is given, the properties for that particular component will be set for that particular type of chart.

    string property (in)

    The property of the component of the plot/chart: textcolor, thickness of the axis line, etc. If not given or empty, a list of properties is returned. If it is given, that particular property for that particular component will be set for that particular type of chart.

    string value (in)

    The new value for the property. If empty, the current value is returned. If the value is "default", the default value will be restored.

    Note, that in some cases an empty value is useful. Use "none" in this case - it can be useful for colours and for formats.

    Below is a more detailed list of the components and properties:

    • Axes come in a wide variety:

      • leftaxis, rightaxis, topaxis, bottomaxis for the plots with a rectangular shape.

      • xaxis, yaxis and zaxis are used for the 3D plots

      • axis, this represents the radial and tangential axes of a polar plot

      All axes have the following properties:

      • color - the colour of the line and the tickmarks

      • thickness - the width of the line of the axis itself, not the tickmarks

      • ticklength - the length of the tickmarks in pixels. A positive value is outward, a negative value is inward.

      • font - the font for the labels and the text at the axis

      • format - the format for rendering the (numerical) labels. For the time axis it is the format for a date and time.

      • textcolor - the colour for the labels and the text.

    • The margin is important for the layout. Currently only the rectangular plots allow the margins to be set: left, right, top and bottom. The values are in pixels.

    • The text component is meant for any text appearing via the plaintext subcommand. The properties are: textcolor, font and anchor (positioning of the text relative to the given coordinates).

    • The background has two properties: outercolor, the colour outside of the actual plot, and innercolor, the colour inside the plot. (Note: only "outercolor" has now been implemented).

    • The legend has three properties: background, border and position. See the legend subcommand for the meaning.

    See the examples in plotdemos7.tcl for it use.

    SCROLLING FOR TIMECHARTS AND GANTT CHARTS

    For two types of plots automatic scrolling management has been implemented: timecharts and Gantt charts. The subcommands hscroll and vscroll associate (existing) scrollbars to the plot, in much the same way as for text and canvas widgets.

    Once the association is made, the scrollbars are automatically updated if:

    • You add an item with a period wider than the current one.

    • You add a vertical line for a time beyond the current bounds.

    • You add an extra item beyond the number that was used to create the chart.

    For instance:

    package require Plotchart
    canvas .c -width 400 -height 200
    scrollbar .y -orient vertical
    scrollbar .x -orient horizontal
    grid .c .y -sticky news
    grid .x -sticky news
    source plotchart.tcl
    set s [::Plotchart::createTimechart .c "1 january 2004" "31 december 2004" 4]
    $s period "Spring" "1 march 2004" "1 june 2004" green
    $s period "Summer" "1 june 2004" "1 september 2004" yellow
    $s vertline "1 jan" "1 january 2004"
    $s vertline "1 apr" "1 april 2004"
    $s vertline "1 jul" "1 july 2004"
    $s vertline "1 oct" "1 october 2004"
    $s vertline "1 jan" "1 january 2005"
    $s vertline "1 apr" "1 april 2005"
    $s vertline "1 jul" "1 july 2005"
    $s milestone "Longest day" "21 july 2004"
    $s milestone "Longest day 2" "21 july 2004"
    $s milestone "Longest day 3" "21 july 2004"
    $s milestone "Longest day 4" "21 july 2004"
    $s milestone "Longest day 5" "21 july 2004"
    $s milestone "Longest day 6" "21 july 2004"
    $s title "Seasons (northern hemisphere)"
    $s vscroll .y
    $s hscroll .x

    The original extent of the chart is from 1 january 2004 to 31 december 2004. But because of the addition of vertical lines in 2005 and more items than was specified at the creation of the chart, both the horizontal and the vertical scrollbar will be enabled.

    ARRANGING MULTIPLE PLOTS IN A CANVAS

    The command plotpack allows you to copy the contents of a plot into another canvas widget. This canvas widget does not act as a composite plot, but it can be saved as a PostScript file for instance: Note: the command simply takes a snapshot of the plots/charts as they are at that moment.

    ::Plotchart::plotpack w dir args

    Copy the contents of the plots/charts into another widget, in a manner similar to the pack geometry manager.

    widget w (in)

    The name of the canvas widget to copy the plots/charts into

    string dir (in)

    The direction of the arrangement - top, left, bottom or right

    list args (in)

    List of plots/charts to be copied.

    For example:

        set p1 [createXYPlot ...]
    set p2 [createBarchart ...]
    ... fill the plots ...
    toplevel .t
    pack [canvas .t.c2 -width ...]
    #
    # Copy the two plots above each other in the new canvas
    #
    plotpack .t.c2 top $p1 $p2
View as RSS news feed in XML
 
Powered by Community Server, by Telligent Systems