0

I can't delete a canvas item from array, using object tag (string)

from Tkinter import *

if __name__=="__main__":

    root=Tk()
    cv=Canvas(root,bg="yellow",width=200,height=200)
    cv.pack()  

    wCell=100
    N=2
    for col in range(N):
        for row in range(N):
            x=50+col*wCell 
            y=50+row*wCell 

            cc=str(row)+str(col)
            print row,col,cc,type(cc)
            R=50
            coords=[x-R,y-R,x+R,y+R]
            clr="cyan"
            cv.create_oval(coords,fill=clr,tags=(cc,))

        #this part does NOT respond. Why? Please help!
        cv.delete((str(11),))
        cv.update()

    root.mainloop()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
G. Kalman
  • 21
  • 2

2 Answers2

2

from Tk doc:

Each item may also have any number of tags associated with it. A tag is just a string of characters, and it may take any form except that of an integer. For example, 'x123' is OK but '123' isn't ...

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
G. Kalman
  • 21
  • 2
0
#this part does NOT respond. Why? Please help!
cv.delete((str(11),))

The above code is the same as this:

tag = str((str(11),))
cv.delete(tag)

When you examine tag you'll see that the value is the string ('11',). Tkinter is going to look for a canvas item literally with the 7-byte tag ('11',). You don't have any items on the canvas with that tag.

Part of the problem is that you are trying to create an object and give it a tag that is a combination of two integers. This is not a valid tag for a canvas item, because tkinter has no way to distinguish the tag from a canvas item identifier which is an integer. Canvas tags can be any arbitrary string except for a sequence comprised only of digits.

In the code that creates the oval, if you want to apply a custom tag then it must not be in the form of an integer. For example, you could prepend a single character to make your tag correct. Then, you just need to use the same tag in your code:

cc="o" + str(row)+str(col)
cv.create_oval(coords, fill=clr, tags=(cc,))
...
cv.delete("o11")
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685