3

I am trying to animate a circle that moves over time but i do not know how to use .after() on Canvas to add a delay before the circle changes position each time. Does anyone know how to do this? Thanks.

my code (i have put a .sleep() where i would like the delay to be):

from tkinter import *
import time
root = Tk()

c = Canvas(root, width = 500, height = 500)
c.pack()

oval = c.create_oval(0, 0, 0, 0)
for x in range(2, 50, 5):
    time.sleep(0.1)
    c.delete(oval)
    oval = c.create_oval(x+50, x+50, x+50, x+50)
EsotericVoid
  • 2,306
  • 2
  • 16
  • 25
Regi
  • 39
  • 1
  • 1
  • 3

1 Answers1

3

Here's a simple example of using .after, derived from your code. As you can see, the .after method needs to be supplied a function to call after the specified delay, so you need to wrap your changes in a function.

import tkinter as tk
root = tk.Tk()

canvas = tk.Canvas(root, width = 500, height = 500)
canvas.pack()
radius = 10
bbox = (-radius, -radius, radius, radius)
oval = canvas.create_oval(*bbox)

def move_oval():
    canvas.move(oval, 1, 1)
    canvas.after(20, move_oval)

# Start moving!
move_oval()

root.mainloop()

If you'd like to see a more complex example, take a look at tk_orbit.py.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182