【发布时间】:2016-10-28 15:52:59
【问题描述】:
我是 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()
【问题讨论】:
-
这似乎是 tkinter 方面的问题,而不是 Python 方面的问题。
-
errr,只需从
balls列表中删除对应的实例,删除的对象不会被迭代。 -
这似乎与“从 [a] 类中删除 [ing] 对象 [s]”没有任何关系。您需要阅读 Tkinter API 以了解如何从游戏中移除对象。
-
@Jean-FrançoisFabre 它们仍将显示在 Tkinter 窗口中。它们也需要从画布中删除。