如何删除 Canvas 文本对象? [英] How do you delete a Canvas text object?
问题描述
例如,这是一个 create_text:
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?
推荐答案
一种方法是使用 对象 ID 所有 Canvas
对象构造函数返回:>
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)
然后你可以使用 Canvas
对象的 delete()
方法如下:
Then afterwards you can use the Canvas
object's delete()
method like this:
self.__canvas.delete(self.text_id)
另一种方法是附加一个 tag 到 Canvas
对象,并使用它:
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")
然后将标记传递给 delete()
方法而不是对象 ID:
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.
标签更强大,因为您可以为多个对象提供相同的标签,然后作为一个组对它们进行操作.相反,一个对象可以通过指定一个元组来附加多个标签:即 tag=("1234", "@special", "posn:13,42")
在构造函数调用中.
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.
要在单击 Button
时发生这种情况,您还需要定义一个函数或方法,当它被点击时调用上述 Canvas
方法之一.叫.然后,在创建按钮小部件时,通过 command=
配置选项指定其名称.
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.
例如(在 class
定义中):
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.
这篇关于如何删除 Canvas 文本对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!