Skip to content Skip to sidebar Skip to footer

How Do You Delete A Canvas Text Object?

This is for example a create_text: self.__canvas.create_text(350, lineVotes, text=str(likesPrinted), font=('calibri', 30), fill='#66FF99', anchor=E) How

Solution 1:

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):

classClass:
    ...

    defcreate_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()
    
    defdelete_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.

Post a Comment for "How Do You Delete A Canvas Text Object?"