删除和删除附加对象 - python

时间:2015-12-29 04:18:27

标签: python tkinter append

使用下面的代码,我可以获取附加的精灵,以便在点击事件中从列表中删除和删除,但遗憾的是,这不是我需要的。我已经在玩了好几个小时试图让它自动删除并在它通过运动类15次循环后从列表中删除。 (如果你需要它,我可以提供帮助。

class projectilesGroup(object):

    def __init__(self, canvas):
        self.canvas = canvas
        self.projectiles = list()
        self.moving = True

    def clicked(self, event, projectile):
        print('clicked:', projectile),

        # remove oval from canvas        
        self.canvas.delete(projectile.oval)

        # remove enemy from list
        self.projectiles.remove(projectile)

    def add_new_projectile(self):
        print(len(self.projectiles))
        if len(self.projectiles) < 5:
            e = projectile(self.canvas)
            # stop new enemy if all enemies are stoped
            e.moving = self.moving
            self.canvas.tag_bind(e.oval, '<Button-1>', lambda event:self.clicked(event, e))
            self.projectiles.append(e)
        else:
            print("You have 5 spells active - I can't add more.")

感谢。

def move(self):
    if repcount < 15:
    if self.moving: # to stop root.after
        if self.direction == 1: # up
             self.y1 -= self.radius
             self.y2 -= self.radius
        elif self.direction == 2: # down
            self.y1 += self.radius
            self.y2 += self.radius
        elif self.direction == 3: # left
            self.x1 -= self.radius
            self.x2 -= self.radius
        elif self.direction == 4: # right
            self.x1 += self.radius
            self.x2 += self.radius
        self.canvas.coords(self.oval, self.x1, self.y1, self.x2, self.y2)
        repcount += 1
        root.after(20, self.move)
    else:
        print('done')

1 个答案:

答案 0 :(得分:1)

首先,每个对象都需要变量来计算运动。当counter计为15时,对象可以自行删除。

对象可以从画布中轻松删除椭圆,因为它具有self.ovalself.canvas

小问题可能是从projectlist移除对象,但您可以访问projectlist

e = projectile(self.canvas, self.projectiles)

编辑:可以这样做

class ProjectilesGroup(object):

    # ...

    def clicked(self, event, projectile):
        print('clicked:', projectile),

        self.remove(projectile)

    def remove(self, projectile):

        # remove oval from canvas        
        self.canvas.delete(projectile.oval)

        # remove enemy from list
        self.projectiles.remove(projectile)

    def add_new_projectile(self):
        print(len(self.projectiles))
        if len(self.projectiles) < 5:
            e = Projectile(self, self.canvas) #parent and canvas

        # ...

class Projectile():

    def __init__(self, parent, canvas):
        self.parent = parent
        self.canvas = canvas

        # ... 


    def move(self):

        # .... 

        else:
            print('done')
            self.parent.remove(self)    

顺便说一句:在文件PEP8中,可以使用&#34; CamelCase&#34;类名 - 如Projectile和ProjectilesGroup。在代码中识别类更容易。有些编辑甚至为CamelCase名称使用不同的颜色(SO使用蓝色)