I'm working with Tkinter and canvas, and I want to make a moving animation. I have a coordinate list:
# coordinates
x = [100, 200, 300, 400]
y = [50, 200, 250, 300]
# starting point
radius = 5
dot = canvas.create_oval(x[0]-radius, y[0]-radius, x[0] radius, y[0] radius, fill="red")
Expected output would be the animation of the "dot" moving like this:
# dot coordinates:
# (100, 50) -> (200, 200) -> (300, 250) -> (400, 300) -> (300, 250) -> (200, 200) -> (100, 50) -> ...
Could you show me how can I make such animation in Tkinter?
Thank you very much!
CodePudding user response:
You could do it with a combination of canvas.coords(dot, ...)
, as @acw1668 suggests ( 1), and tkinter's after()
method:
import tkinter as tk
from itertools import cycle
RADIUS = 5
DELAY = 1000 # milliseconds
WIDTH, HEIGHT = 500, 500
coordinates = [(100, 50), (200, 200), (300, 250), (400, 300)]
def move():
x, y = next(cycled_coordinates)
canvas.coords(dot, x-RADIUS, y-RADIUS, x RADIUS, y RADIUS)
canvas.after(DELAY, move)
cycled_coordinates = cycle(coordinates)
master = tk.Tk()
canvas = tk.Canvas(master, width=WIDTH, height=HEIGHT)
canvas.pack()
x, y = next(cycled_coordinates)
dot = canvas.create_oval(x-RADIUS, y-RADIUS, x RADIUS, y RADIUS, fill='red')
canvas.after(DELAY, move)
master.mainloop()