Advanced Search
Mail us
Home    Manuel    Links    Faq    Submit a tcl/tk Reference    Contact Us

    Some examples tcl/tk codes     Man of Bwidget     Man of blt     mkwidget screenshots     TkOgl     Video Demo real.


  How can I use a list of coordinates in a variable to create a polygon (or any other item)?
 
 This is actually a pure Tcl question, but it comes up frequently in this
context, so here we go...

All canvas items require two or more coordinates on creation, which
define the initial position and/or shape of the item.  If you have each
coordinate in a separate variable, or you are using a constant value,
then creating canvas items is simple.  For example:

    .myCanvas create rectangle $x1 $y1 $x2 $y2 -fill blue
    .myCanvas create text 100 250 -text "Hello, world"

Many times, though, the coordinates don`t each exist in a separate
variable.  They may be a list in a single variable that was read from a
file, or returned from some calculation routine, or extracted from some
other list of coordinates.  In this case, you need to break the list of
coordinates up before the canvas command is executed.  Use the `eval`
commands for this.  Here are several examples:

# Example 1
# Given a list of two coordinates, create a text item
#
set coords {150 50}
eval .myCanvas create text $coords -text hello

# Example 2
# Here`s a routine that returns coordinates for a rectangle centered
# around a point, and some example uses.
#
proc CenteredRectangle {x y width height} {
    return [list [expr {$x - $width/2.0}]  [expr {$y - $height/2.0}]  [expr {$x + $width/2.0}]  [expr {$y + $height/2.0}]]
}
eval .myCanvas create rectangle [CenteredRectangle 80 5 10 75]
eval .myCanvas create rectangle [CenteredRectangle 5 80 75 10]
eval .myCanvas create oval [CenteredRectangle 140 110 75 50]

# Example 3
# Here`s a routine which creates a text label surrounded by
# a rectangle, with both of them centered around a given point.
#
proc CenteredBoxLabel {w x y text} {
    set id [$w create text $x $y -text $text -anchor center]
    eval $w create rectangle [$w bbox $id]
}
CenteredBoxLabel .myCanvas 33 42 "Hello, world"

If you have a list of coordinate pairs, e.g. {{25 10} {30 12} {35 14}},
then an extra step is required to make it a flat list.  Try this:

# Example 4
# Starting with a list of pairs...
#
set coordPairs {{25 10} {30 12} {35 14}}

# ... flatten out the list into just a list of numbers (as in
# the above examples).
#
set flatList [eval concat $coordPairs]

# Now, follow the same strategy as in the examples above.
#
eval .myCanvas create line $flatList

In summary, carefully read the docs for `eval`, `concat`, and `list` so
that you can combine the coordinate data with the `canvas create`
command to form a valid Tcl command which can be executed.