有没有办法销毁存储在列表中的 Tkinter 对象?

问题描述 投票:0回答:1

我正在尝试在 Tkinter 中显示大量出现和消失的对象。我将它们存储在一个普通列表中,以便于访问并能够轻松地遍历它们。我还希望一些对象消失而不回来(因此被完全删除)。

我尝试使用

.destroy()
因为这应该可以破坏 Tkinter 中的对象:

loc = 0
list_with_objects.append(create_oval(1, 2, 3, 4)
list_with_objects[loc].destroy()

但是,这不起作用,只会给我以下错误消息:

AttributeError: 'int' object has no attribute 'destroy'
任何关于我如何做到这一点的想法都将非常感激。 这是我的完整代码:

from random import choices, randint
import tkinter


class World(tkinter.Canvas):
    def __init__(self, master, size):

        self.xLim = size[0]
        self.yLim = size[1]

        super().__init__(master, width=self.xLim, height=self.yLim, bg='#27c945')
        self.pack()

        self.organisms = []
        self.organTags = []

        self.run()


    def run(self):

        for organism, organTag in zip(self.organisms, self.organTags):
            organism.movement()
            self.move(organTag, organism.xDis, organism.yDis)
            
            if organism.x >= self.xLim - 10 or organism.x <= 10:
                organism.xDis *= -1
            if organism.y >= self.yLim - 10 or organism.y <= 10:
                organism.yDis *= -1
                
        toKill = []
        for loc in range(len(self.organisms)):
            if choices([0, 1], [90, 10])[0] == 1:
                toKill.append(loc)

        self.killOrganism(*toKill)
        self.newOrganism()

        self.after(25, self.run)


    def newOrganism(self):
        new = organism(self.xLim, self.yLim)
        self.organisms.append(new)
        self.organTags.append(self.create_oval(new.x - 10, new.y - 10, new.x + 10, new.y + 10, fill='black'))


    def killOrganism(self, *args):
        for loc in sorted(args, reverse=True):
            self.organTags[loc].destroy()
            self.organTags.pop(loc)
            self.organisms.pop(loc)
            

class organism():
    def __init__(self, xLim, yLim):
        self.x = randint(10, xLim - 10)
        self.y = randint(10, yLim - 10)

        self.xLim = xLim - 10
        self.yLim = yLim - 10

        self.xDis = randint(-1, 1)
        self.yDis = randint(-1, 1)


    def movement(self):
        if choices((0, 1), [99, 1]) == [1]:
            self.xDis = randint(-3, 3)
            self.yDis = randint(-2, 2)

        self.x += self.xDis
        self.y += self.yDis


worldWidth = 1280
worldLenght = 960
Map = tkinter.Tk()
Map.geometry(str(worldWidth) + 'x' + str(worldLenght))
field = World(Map, (worldWidth, worldLenght))
field.mainloop()
python arrays tkinter tkinter-canvas destroy
1个回答
1
投票

create_oval
返回一个没有
int
方法的
destroy
。幸运的是,这个 int 是画布中形状的引用。您可以使用
your_canvas.delete(ref)
删除它。所以在你的代码中:

def killOrganism(self, *args):
    for loc in sorted(args, reverse=True):
        self.delete(self.organTags[loc])
        self.organTags.pop(loc)
        self.organisms.pop(loc)
© www.soinside.com 2019 - 2024. All rights reserved.