我正在使用Tkinter画布制作一个游戏,其中点会在屏幕上移动。我使用
我的问题是,当这些点移动时,它们似乎会留下轨迹。我制作了一个简化的示例来演示我的问题。
tkinter.Canvas.create_oval(...)
将每个点放置在一个位置,并使用tkinter.Canvas.move(pointID,delta_x,delta_y)
移动点。我的问题是,当这些点移动时,它们似乎会留下轨迹。我制作了一个简化的示例来演示我的问题。
from tkinter import Canvas,mainloop,Tk
import numpy as np
import random
import traceback
import threading
import time
from queue import Queue
class Point:
def __init__(self,the_canvas,uID):
self.uID = uID
self.location = np.ones((2)) * 200
self.color = "#"+"".join([random.choice('0123456789ABCDEF') for j in range(6)])
self.the_canvas = the_canvas
self.the_canvas.create_oval(200,200,200,200,
fill=self.color,outline=self.color,width=6,
tags=('runner'+str(self.uID),'runner'))
def move(self):
delta = (np.random.random((2))-.5)*20
self.the_canvas.move('runner'+str(self.uID),delta[0],delta[1])
def queue_func():
while True:
time.sleep(.25)
try:
next_action = the_queue.get(False)
next_action()
except Exception as e:
if str(e) != "":
print(traceback.format_exc())
the_queue = Queue()
the_thread = threading.Thread(target=queue_func)
the_thread.daemon = True
the_thread.start()
window = Tk()
window.geometry('400x400')
the_canvas = Canvas(window,width=400,height=400,background='black')
the_canvas.grid(row=0,column=0)
points = {}
for i in range(100):
points[i] = Point(the_canvas,i)
def random_movement():
while True:
for point in points.values():
point.move()
the_queue.put(random_movement)
mainloop()
结果大致如下:
我需要能够干净地移动点,而不会留下任何痕迹。
- 我尝试更改
move()
函数,使每个点根据其标签被删除并在新位置重新绘制,但这导致相同的问题。 - 我尝试在
Canvas.oval
配置中使用fill=''
和outline=''
,但这没有帮助。 - 这些像素试验的行为似乎是不稳定的,就像它们会随着时间的推移消失,只留下有限数量的足迹。
- 我尝试从移动循环中删除
time.sleep(.2)
,这似乎使问题更加明显。
- 我发现清除这些流氓彩色像素的唯一方法是运行
canvas.delete("all")
,因此目前我的唯一解决方案是不断删除和重新绘制所有内容。这对我来说似乎不是一个好的解决方案。
有什么好的方法可以避免这些“像素痕迹”? 对我来说,它似乎只是一个漏洞,但也许我在某个地方犯了错误。
after()
循环时,伪影大部分会消失。但是仍然存在一些伪影。 - Mike - SMT