0
votes

I tried the following test (see snippet hereunder):

and it always returns 0 regardless of the fact that the canvas object (the rectangle in this case) has been created (with "create") or deleted (with "delete").

Is there another way to check if a canvas object exists or has successfully been deleted in Tcl/Tk ?

Thanks !

Serge Hulne

    ############

    tk::canvas .can
    set r1 [.can create rect 30 10 120 80  -outline #fb0 -fill #fb0]
    set r2 [.can create rect 150 10 240 80 -outline #f50 -fill #f50]
    set r3 [.can create rect 270 10 370 80 -outline #05f -fill #05f]
    pack .can


    ##
    ##info exists does not work for canvas elements : it always returns 0
    set rcc [info exists $r2]
    puts "rcc = $rcc"


    if {[info exists $r2]} {
        puts "$r2 exists !"
       .can delete $r2
        puts [info exists $r2]
     } else {
         puts "$r2  does not exist !"
         set rc [info exists $r2]
         puts "rc = $rc  "
    }
    ##
    ##        
    wm title . "colors"
    wm geometry . 400x100+300+300

    ##########
1

1 Answers

0
votes

info exists is used to check whether a variable exists. A canvas widget is not a variable, it is a widget.

As such, you need to use winfo exists to check whether a canvas exists:

winfo exists .can

But then again, what you used as r2 in your code is an item within the canvas, and there is no command to check its existence as far as I know. However, you can use .can find all to get a list of all the items in the canvas and compare it to r2:

% tk::canvas .can
% set r1 [.can create rect 30 10 120 80  -outline #fb0 -fill #fb0]
% set r2 [.can create rect 150 10 240 80 -outline #f50 -fill #f50]
% set r3 [.can create rect 270 10 370 80 -outline #05f -fill #05f]

% puts $r2
2  # Because it is the second item created
% .can find all
1 2 3

You can then do something like lsearch -exact [.can find all] $r2 and if you get something not -1, know that this item exists.


Though if you use unique tags with your items, you can use .can find withtag to verify its existence:

% tk::canvas .can
% set r1 [.can create rect 30 10 120 80  -outline #fb0 -fill #fb0 -tags t1]
% set r2 [.can create rect 150 10 240 80 -outline #f50 -fill #f50 -tags t2]
% set r3 [.can create rect 270 10 370 80 -outline #05f -fill #05f -tags t3]

% .can find withtag t2
2  # which is equal to $r2