Animating the racers

To animate our racers, we're going to use the Canvas.move() method. move() takes an item ID, a number of x pixels, and a number of y pixels, and moves the item by that amount. By using random.randint() and some simple logic, we can generate a series of moves that will send each racer on a meandering path towards the finish line.

A simple implementation may look like this:

def move_racer(self):
    x = randint(0, 100)
    y = randint(-50, 50)
    t = randint(500, 2000)
    self.canvas.after(t, self.canvas.move, self.id, x, y)
    if self.canvas.bbox(self.id)[0] < self.canvas.right:
        self.canvas.after(t, self.move_racer)

This isn't really what we want, though; the problem is that move() happens instantaneously, causing the bug to jump across ...

Get Python GUI Programming with Tkinter now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.