How do I delete a ball after it has been created? I created a class for a ball and have an array generating 20 balls on screen. The balls are created in random positions with random speeds. When the ball is clicked on, it is supposed to disappear. I can't seem to get this to function properly. Please help.
from Tkinter import *
import random
import time
import math
import pygame
canvasWidth=480
canvasHeight=320
root= Tk()
canvas=Canvas(root,width=canvasWidth,height=canvasHeight, bg='white')
root.title('RaspPi')
canvas.pack()
class Ball:
def __init__(self):
self.ballSize = 30
self.xposition = random.randint(0 + self.ballSize, canvasWidth - self.ballSize)
self.yposition = random.randint(0 + self.ballSize, canvasHeight - self.ballSize)
self.shape=canvas.create_oval(self.xposition,self.yposition,self.xposition+self.ballSize,self.yposition+self.ballSize, fill='black',activefill="grey",width=0,tag="shape")
self.xspeed=0
self.yspeed=0
self.ballDeleted=False
canvas.tag_bind("shape","<Button-1>",self.ballDelete)
while self.xspeed<=0.5 and self.xspeed>=-0.5:
self.xspeed = random.randrange(-3,3)
while self.yspeed <= 0.5 and self.yspeed >= -0.5:
self.yspeed = random.randrange(-3,3)
def move(self):
canvas.move(self.shape, self.xspeed, self.yspeed)
pos = canvas.coords(self.shape)
if pos[2] >= canvasWidth or pos[0] <= 0:
self.xspeed = -self.xspeed
if pos[3] >= canvasHeight or pos[1] <= 0:
self.yspeed = -self.yspeed
def ballDelete(self,event):
canvas.delete(self.shape)
balls=[]
for i in range(20):
balls.append(Ball())
while True:
for ball in balls:
if ball.ballDeleted==False:
ball.move()
else:
balls.remove(ball)
root.update()
time.sleep(0.01)
root.
mainloop()
Aucun commentaire:
Enregistrer un commentaire