canvas text


text is one of the standard canvas item types

Getting Text Dimensions

To get the dimensions of a text item, use [canvas bbox]. Examples:

A Graph plotter


from simple to complex:

expanding/collapsing text item

Rotated Text

Rotated canvas text
Rotate text on a canvas

Text Items as textvariables

RS: With the following few lines you can associate one (or any number of) text items to update by traceing when a variable changes value:

proc canvas'text'update {canvas tag _var - -} {
    upvar $_var var
    $canvas itemconfig $tag -text $var
#---------------------- usage & demo code
pack [canvas .c]
.c create text 100 100 -tag vartext
trace add variable testing write [list canvas'text'update .c vartext]
set testing "hello, world!" ,# yet another way to say it...

The following variation packages both the definition and the implementation of the trace into the same command, differentiated by the number of arguments:

proc canvas'textvar {canvas tag _var args} {
    upvar 1 $_var var
    if { [llength $args] } {
        $canvas itemconfig $tag -text $var
    } else {
        uplevel 1 trace add variable $_var write \
            [list [list canvas'textvar $canvas $tag]]
canvas'textvar .c vartext testing
set testing "hello again!"

Text item background

Text items are on a transparent background. You can give them an opaque background by first creating the text, then determining its b(ounding )box, drawing a rect with equal -fill and -outline, and finally raising the text item again. Example, where this happens on demand when the user clicks on a text:

$canvas bind text <1> {
    %W create rect [%W bbox current] -fill white -outline white -tag bg
    %W lower bg text
$canvas bind text <3> {%W delete bg} ;# RS