【问题标题】:Issue deleting a canvas object from class从类中删除画布对象的问题
【发布时间】:2012-12-31 17:35:37
【问题描述】:

我在从类中删除画布对象时遇到问题。

我创建了一个名为 fRectangle 类型的对象。然后我需要删除这个对象。 Python 会删除f,但不会删除 Frame 上的画布对象。我不知道问题出在哪里。

from tkinter import *


class Rectangle():

    def __init__(self, coords, color):   
        self.coords = coords
        self.color = color   

    def __del__(self):
        print("In DELETE")
        del self
        print("Goodbye")

    def draw(self, canvas):
        """Draw the rectangle on a Tk Canvas."""
        print("In draw ")
        print("Canvas  =  ",canvas)
        print("self = ",self)
        print("bild canvas = ",canvas.create_rectangle(*self.coords, fill=self.color))


root = Tk()
root.title('Basic Tkinter straight line')
w = Canvas(root, width=500, height=500)

f = []
f = Rectangle((0+30*10, 0+30*10, 100+30*10, 100+30*10), "yellow")
print("Draw object", f.draw(w), f)
f.__del__()
del f

w.pack()
mainloop()

【问题讨论】:

  • Canvas 对象被分配给引用 w。那是您要删除的内容吗?
  • 是的,如果我这样做 w.delete(f) 什么都没有发生

标签: python class canvas


【解决方案1】:

好的,您遇到的问题是您开始创建一个 Rectangle 对象供您自己使用,这看起来很合理,但您需要努力实现它。

无论如何简单地完成你想做的事情(没有你的对象):

# draws a rectangle and returns a integer
rectangle_id = c.create_rectangle(*(0, 0, 30, 30), fill="yellow")
c.delete(rectangle_id) # removes it from the canvas

要使用Rectangle 对象完成您想要的操作,我建议您在绘制它时使用一个属性来存储 id 并实现一个可以删除它的方法。当不再有对您的对象的任何引用时,您可能希望使用 __del__ 方法将其删除。这可以做到,但您应该注意一些警告(超出我的回答范围......请参阅:http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/)。我个人会选择显式调用一个方法来从视图中删除对象表示,以避免所有这些废话:)。

这里我忽略了很多设计决策,我建议你在这里对 OO 的使用考虑一下,或者在你对 tkinter 有更好的理解之前避免使用它。

【讨论】:

  • 我在 Rectangle 类中创建了一个 self.rectangle_id 问题就消失了,非常感谢,新年快乐
猜你喜欢
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-14
  • 2019-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多