Python:如何从类中删除对象?

2024-04-24 07:31:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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()

Tags: 代码posimportselfrandomrootcanvasshape
1条回答
网友
1楼 · 发布于 2024-04-24 07:31:26

使用类画布的bind方法并删除单击的椭圆。for循环应该有一个异常处理,因为删除的对象不能有坐标或速度。del()函数通常用于删除对象。在

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',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())


def click(event):
    if canvas.find_withtag(CURRENT):
        canvas.delete(CURRENT)

canvas.bind("<Button-1>", click)

while True:
    for ball in balls:
        try:
            ball.move()
        except:
            del(ball)

    root.update()
    time.sleep(0.01)

root.mainloop()

更新

如果列表pos不为零,只需检查您的方法move。如果它是零,只需删除对象本身。如果你只是删除画布是可以的,但是如果你关心内存的使用,这是我能想到的最好的选择。在

^{pr2}$

相关问题 更多 >