如何阻止tkinter canvas widget/after方法跳过列表中的元素



我正在尝试创建一个每秒更新的行。此更新需要显示在屏幕上,因此您应该能够在窗口中看到更改。例如,下面的每一行都应该在一秒钟后运行。

canvas.create_line(1, 2, 10, 20, smooth="true")
canvas.create_line(1, 2, 10, 20, 50, 60, smooth="true")
canvas.create_line(1, 2, 10, 20, 50, 60, 100, 110, smooth="true")

这就是我目前所拥有的:

def make_line(index):
while index < len(database):
x, y, z = database[index]
# database is a list of tuples with numbers for coordinates
coordinates.append(x) # coordinates is an empty list
coordinates.append(y)
#don't need z since 2D map
index += 1
if index == 2:
# noinspection PyGlobalUndefined
global line
line = canvas.create_line(coordinates, smooth="true") 
# same as canvas.create_line(1, 2, 10, 20, smooth="true")
elif index > 2:
canvas.after(1000, lambda: canvas.coords(line, coordinates))
# it's jumping from the 1st to the 4th element
else:
pass
make_line(0)

我认为问题出在canvas.after方法和canvas.coords当索引=3时,当它运行该行时,坐标已经有1、2、10、20、50、60、100和110,而它应该只有1、2,10、20,50和60。提前谢谢。

我最终不得不将while循环移到函数之外,并添加了root.update_idletasks((和root.update((,而不是使用root.mainloop((。从这篇文章中我了解到,你的程序基本上会停止在mainloop,而更新会允许程序继续。这就是我最终得到的:

def add_coordinates(index):
x, y, z = database[index]
coordinates.append(x)  # coordinates is an empty list
coordinates.append(y)
ind = 0 # ind means index
while ind < len(database):
if ind < 2:
add_coordinates(ind)
elif ind == 2:
trajectory = canvas.create_line(coordinates, smooth="true")
add_coordinates(ind)
canvas.after(1000)
elif ind > 2:
add_coordinates(ind)
canvas.after(1000, canvas.coords(trajectory, coordinates))
else:
pass
ind += 1
root.update_idletasks()
root.update()

当然,我在文件的开头有import语句,在文件的最后有root.mainloop((。

最新更新