0

I have implemented the following code for creating an animation consisting of lines with tkinter (df is just a Pandas dataframe). The problem is that I just see the result but somehow the sleep is not executed (that means there is no animation of lines). How can this be achieved? Moreover, the sleeps are most of the time pretty small (a few milliseconds), so I don't know if this is possible.

Second, I would like to save the animation as a video (e.g. mpeg). A solution would be to store the images and then creating the video but this is a bit cumbersome (and I would get a lot of images). Is there another possibility (perhaps using a different approach than tkinter)?

root = Tk()
root.title("User {}".format(user_id))
canvas = Canvas(width=1920, height=1200, bg='white')
canvas.pack(expand=YES, fill=BOTH)
prev = None
temp_prev = None

for index, row in df.iterrows():
    if prev is not None:
        canvas.create_line(prev["x"], prev["y"], row["x"], row["y"])

    if row["action"] == "ACTION_UP":
        prev = None
    else:
        prev = row

    if temp_prev is not None:
        sleep(0.04)

    temp_prev = row

root.mainloop()

EDIT: I have update the code using after(). Unfortunately, again just the final result is plotting but there is no animation.

root = Tk()
root.title("User {}".format(user_id))
canvas = Canvas(width=1920, height=1200, bg='white')
canvas.pack(expand=YES, fill=BOTH)
root.after(0, add_line(canvas, df.iloc[1], 0, df, root))
root.mainloop()

def add_line(canvas, next, idx, df, root):
    row = df.iloc[idx]
    idx = idx + 1
    if row["action"] != "ACTION_UP":
        canvas.create_line(row["x"], row["y"], next["x"], next["y"])

    next = df.iloc[idx + 1]

    if (idx + 2) < len(df):
        root.after(int(next['timestamp_offset'] - row['timestamp_offset']), add_line(canvas, next, idx, df, root))
    else:
        return
machinery
  • 5,972
  • 12
  • 67
  • 118
  • Don't use `sleep()` in tkinter. It will just freeze the instance. Instead you need to use `after()`. You will likely need to reformat your code to compensate for how `after()` works but it is the correct method within tkinter for setting up a delayed execution of code. Judging by your for loop You will likely need to set up a function or 2 to compensate for the change in behavior from what sleep() does to what after() does. – Mike - SMT Jun 08 '18 at 15:12
  • @Mike-SMT Thanks a lot. I have updated my question using after. Unfortunately it still does not work. – machinery Jun 10 '18 at 12:54

0 Answers0