How do you delete a Canvas text object?

ぃ、小莉子 提交于 2019-12-19 11:21:39

问题


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?


回答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 list 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 definiton):

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.


来源:https://stackoverflow.com/questions/28840882/how-do-you-delete-a-canvas-text-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!