我创建了一个类对象Dot()
,一个函数update()
更新了它的位置,然后在canvas
上生成了它的许多实例,并将它们添加到列表中。我运行一个循环,不断更新点的位置,这很好,但我也想在每次循环运行时删除Dot()
的一个实例。
我尝试了很多方法但没有成功。通过使用canvas.delete()
函数,我只“冻结”实例化,但它仍然在屏幕上。我该如何解决这个问题?
import numpy as np
import random
import time
from tkinter import *
#create Canvas#
screen = Tk()
hei = 600
wid = 600
canvas = Canvas(screen,width=wid,height=hei)
canvas.pack()
colors = ["red", "green", "blue"]
class Dot:
def __init__(self):
self.l = random.randrange(100,200)
self.t = random.randrange(100,200)
self.l2= self.l-10
self.t2 = self.t-10
color = random.choice(colors)
self.shape = canvas.create_oval(self.l, self.t, self.l2, self.t2, fill=color)
self.speedx = random.randrange(1,3)
self.speedy = random.randrange(1,3)
def update(self):
canvas.move(self.shape, self.speedx, self.speedy)
pos = canvas.coords(self.shape)
jitter = random.randrange(0,200)
if pos[2] >= wid+jitter or pos[0] <= -jitter:
self.speedx *= -1
if pos[3] >= hei+jitter or pos[1] <= -jitter:
self.speedy *= -1
dots = []
for i in range(100):
dots.append(Dot())
while True:
del dots[-1]
canvas.delete(dots[-1])
for dot in dots:
dot.update()
screen.update()
time.sleep(0.005)
screen.mainloop()
答案 0 :(得分:1)
delete
方法获取画布项的标识符,而不是画布项本身。
此外,您可能应该在超时功能中删除,否则GUI将无法正常运行。
试试这段代码:
import random
from tkinter import *
screen = Tk()
hei = 600
wid = 600
canvas = Canvas(screen, width=wid, height=hei)
canvas.pack()
colors = ["red", "green", "blue"]
class Dot:
def __init__(self):
self.l = random.randrange(100, 200)
self.t = random.randrange(100, 200)
self.l2 = self.l-10
self.t2 = self.t-10
color = random.choice(colors)
self.shape = canvas.create_oval(self.l, self.t, self.l2, self.t2, fill=color)
self.speedx = random.randrange(1, 3)
self.speedy = random.randrange(1, 3)
def update(self):
canvas.move(self.shape, self.speedx, self.speedy)
pos = canvas.coords(self.shape)
jitter = random.randrange(0, 200)
if pos[2] >= wid+jitter or pos[0] <= -jitter:
self.speedx *= -1
if pos[3] >= hei+jitter or pos[1] <= -jitter:
self.speedy *= -1
dots = []
for i in range(100):
dots.append(Dot())
def timeout():
if dots:
canvas.delete(dots[-1].shape)
del dots[-1]
for dot in dots:
dot.update()
screen.after(5, timeout)
screen.after(5, timeout)
screen.mainloop()
(使用Python 3测试)