1

I'm trying to create a line that updates every second. This update needs to show up on the screen, so you should be able to see the change in the window. For example, each of the lines below should run after a second.

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")

This is what I have so far:

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)

I believe the problem is with the canvas.after method and canvas.coords By the time it runs that line when index = 3, coordinates already has 1, 2, 10, 20, 50, 60, 100, and 110 when it should only have 1, 2, 10, 20, 50, and 60. Thanks in advance.

1 Answers1

1

I ended up having to move the while loop outside the function and adding root.update_idletasks() and root.update() instead of having root.mainloop(). From this post I learned that your program will basically stop at mainloop while update will allow the program to continue. This is what I ended up with:

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

Of course, I have things like import statements at the beginning and root.mainloop() at the very end of the file.