Updated 2011-11-29 02:51:04 by RLE

Richard Suchenwirth 2005-08-16 - A colleague asked whether the Tk canvas has balloon help (little yellow windows showing some text) built-in.

I said no, but it'll be easy to make them. It turned out that there's some pitfalls, though: deleting a cballoon caused an <Enter> event on the underlying item, if the cursor was on the balloon, leading to a tight make-delete loop which hung the demo app. Delaying the deletion by a millisecond helped.

Here is the code:
 package require Tk

 proc cballoon {w tag text} {
    $w bind $tag <Enter> [list cballoon'make $w $text]
    $w bind all  <Leave> [list after 1 $w delete cballoon]
 }

 proc cballoon'make {w text} {
    foreach {- - x y} [$w bbox current] break
    if [info exists y] {
        set id [$w create text $x $y -text $text -tag cballoon]
        foreach {x0 y0 x1 y1} [$w bbox $id] break
        $w create rect $x0 $y0 $x1 $y1 -fill lightyellow -tag cballoon
        $w raise $id
    }
 }
#---------------------------------------------------- Test
 pack [canvas .c]
 set id [.c create oval 10 10 110 110 -fill red]
 cballoon .c $id "This is a red oval"

 .c create rect 130 30 190 90 -fill blue -tag rect
 cballoon .c rect "This is\na blue square"

 bind . <Escape> {exec wish $argv0 &; exit}

tklib now has a tooltip implementation that also supports items on a canvas. The code works 'as is' against zinc canvases as well.