How do you delete a Canvas text object?

user4351838 picture user4351838 · Mar 3, 2015 · Viewed 9.7k times · Source

This is for example a create_text:

self.__canvas.create_text(350, lineVotes, text=str(likesPrinted),
                          font=("calibri", 30), fill="#66FF99", anchor=E)

How could I delete this with a button?

Answer

martineau picture martineau · Mar 3, 2015

One way to do it is by using the object ID that all Canvas object constructors return:

self.text_id = self.__canvas.create_text(350, lineVotes,
                                         text=str(likesPrinted),
                                         font=("calibri", 30),
                                         fill="#66FF99", anchor=E)

Then afterwards you can use the Canvas object's delete() method like this:

self.__canvas.delete(self.text_id)

Another way is to attach a tag to the Canvas object, and use that:

self.__canvas.create_text(350, lineVotes,
                          text=str(likesPrinted),
                          font=("calibri", 30), fill="#66FF99", anchor=E,
                          tag="some_tag")

And then pass the tag to the delete() method instead of the object ID:

self.__canvas.delete("some_tag")

The name of a tag can be any string that does not contain white space or periods.

Tags are more powerful because you can give the same one to multiple objects and then act on them as a group. Conversely, an object can have more than one tag attached to it by specifying a tuple of them: i.e. tag=("1234", "@special", "posn:13,42") in the constructor call.

To make this happen when a Button is clicked, you would need to also define a function or method that makes a call to one of the above Canvas methods when it's called. Then, when creating the button widget, specify its name via the command= configuration option.

For example (within a class definition):

class Class:
    ...

    def create_widgets(self):
        self.text_id = self.__canvas.create_text(350, lineVotes, text=str(likesPrinted),
                                                 font=("calibri", 30), fill="#66FF99", 
                                                 anchor=E)
        self.delete_btn = Button(root, text="Delete text", command=self.delete_text)
        self.delete_btn.pack()
    
    def delete_text(self):
        """ Delete the canvas text object. """
        if self.text_id:
            self.__canvas.delete(self.text_id)
            self.text_id = None  # To avoid multiple deletions.