2015-12-29 34 views
-1

隨着下面的代碼,我可以得到附加的精靈刪除和點擊事件列表中刪除,但遺憾的是,這不是我所需要的。我已經花了幾個小時試圖讓它自動刪除,並在它通過運動類15次後從列表中刪除。 (我可以提供,如果你需要它幫助我。刪除和刪除附加的對象-python

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

首先,每個對象都需要變量來計算運動。當counter數到15,然後對象可以刪除本身。

對象可以easely從畫布上刪除橢圓形,因爲它有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)  

BTW:在文檔PEP8有有意使用「CamelCase」類名 - 比如Projectile和ProjectilesGroup。在代碼中識別類是很容易的。有些編輯甚至對CamelCase名稱使用不同的顏色(SO使用藍色)

+0

是的我有一個圍繞運動類的專櫃 –

+0

看到新的編輯。 –

+0

甜美的感謝,我得到它的工作 –