user4351838
user4351838

Reputation:

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 could I delete this with a button?

Upvotes: 7

Views: 22418

Answers (2)

navalega0109
navalega0109

Reputation: 402

Instead of deleting the text of canvas you can make blank or re-write with help of canvas.itemconfig(text_id_name, text="strg text you want to change")

def start():
    canvas.itemconfig(text_id, text="Hello World")


start_btn = Button(text="Start", command=start)

text_id = canvas.create_text(text="Default Text To Start"))

Output

On start button click it'll change to Hello World.

Upvotes: 0

martineau
martineau

Reputation: 123491

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.

Upvotes: 15

Related Questions