我是python新手,在对象类方面有点麻烦。我创造了一个代码,就是球物体从墙上反弹。我想删除一个球后,它已被点击。我试过几种不同的方法来做这件事,但它们都导致了错误。下面是我的代码球反弹从墙上。如何编辑此代码,以便在单击球后将其删除?谢谢!在
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()
使用类画布的bind方法并删除单击的椭圆。for循环应该有一个异常处理,因为删除的对象不能有坐标或速度。del()函数通常用于删除对象。在
更新
如果列表
^{pr2}$pos
不为零,只需检查您的方法move
。如果它是零,只需删除对象本身。如果你只是删除画布是可以的,但是如果你关心内存的使用,这是我能想到的最好的选择。在相关问题 更多 >
编程相关推荐