jeudi 30 juin 2016

Python: how to delete object from class?


I'm new to python and having a little trouble with object classes. I have created code were ball objects bounce off the side of the wall. I would like to delete a ball after it has been clicked on. I have tried several different methods of doing this but they have all resulted in errors. Below is my code for the balls bouncing off the walls. How can I edit this code to have the balls deleted once they are clicked? Thanks!

from Tkinter import *
import random
import time

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)
            self.xspeed = random.randrange(-3,3)
            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


balls=[]
for i in range(20):
    balls.append(Ball())

while True:
    for ball in balls:
        ball.move()

    root.update()
    time.sleep(0.01)

root.mainloop()

Aucun commentaire:

Enregistrer un commentaire