Turtle Animation

Animation

Animation means moving the images on the screen. The turtle module can be used to do animation of images. The animation using LOGO, Tkinter, and Pygame was done on the previous pages. Let us now do animation with the turtle module.

For animation control, we will use the following turtle module’s functions. These functions were described on an earlier page.  They are repeated here for convenient reference.

Animation Turtle Module Functions

turtle.delay(delay) Function:

Syntax:

turtle.delay(delay=None), where delay is a positive number.

This function sets a time delay between two consecutive frame updates.  The higher the delay number, the slower the animation. Example: screen.delay(5) adds a 5 milli-seconds delay between the frames.

turtle.tracer(n,delay) Function:

Syntax:

turtle.tracer(n=Nonedelay=None), where n and delay are non-negative integers.

The argument n updates every nth screen. The second argument delay sets the delay as explained above (sets a delay for drawing updates).

Example: screen.tracer(5,20) will do every 5th screen update with a delay of 20 milliseconds between screen updates.

Note: Turtle.tracer(0) turns animation OFF.

turtle.update() Function:

The turtle.update() function performs a Turtle Screen update. The update() function is used when the tracer() is OFF.  The update() function tells Python to refresh the window with the new image. Screen.update() function is used whenever we want the screen to be updated with the latest version of the drawing.

More details about turtle animation are at this link.

Let us now create a few animation programs using the turtle module.

Make the Turtle Walk Across the Screen

For our first animation program, we will animate the turtle to move across the screen in the x-direction.

In each iteration of the while loop, the turtle moves by a few pixels. As Python computes the new position of the turtle, we need to make sure that each frame is completed before it is displayed. This is done by using the function screen.tracer(0). This function tells the Screen to not show anything until the frame has been completed. After the frame is completed, we display the screen with the updated image using the function screen.update().

The while loop continues to move the turtle image and update the screen frame by frame with the turtle’s new position.

Here is the turtle walk program.

PROGRAM EXAMPLE: TURTLE WALK ANIMATION

Program name: turtle_walk_animation_py

1  # This program animates the turtle to walk across the screen.
2  import turtle
3  window = turtle.Screen()
4  window.setup(320,320)   # Set Window size.
5  window.tracer(0)        # Turn-off animation.
6  
7  TTL = turtle.Turtle()
8  TTL.speed(0)
9  TTL.shape("turtle")     # Select turtle's shape.
10  TTL.penup()
11  TTL.goto(-300, 0)       # Set turtle's starting position.
12  
13  while True:
14      window.update()     # In each while loop, refresh the window with the new drawing.
15      TTL.forward(0.01)
16  window.exitonclick()

Detailed Line-by-line Program explanation:

Line 1): Import turtle module.

In Line 2), we name the turtle screen as “window”.

Line 3): Set the window size a width = 320 pixels and height = 320 pixels.

In Line 5, the window.tracer(0) function turns OFF animation.

Line 7: Let us name our turtle “TTL”.

Line 8: Set the speed at which the turtle moves across the screen. The TTL.speed(0) function has a special meaning. It turns off the animation and the turtle goes as fast as possible.

In Line 9:, the TTL.shape(“turtle”) function selects the shape of the turtle as “turtle”.

Line 10: TTL.penup() function moves the pen up so that the turtle does not draw as it moves on the screen.

Line 11: TTL.goto(-300, 0) statement initializes the starting position of the turtle as (-300,0)

Lines 13 – 15: This is the while loop as described above

Run this program on your computer and watch the turtle walk across your screen.

Animation Turle Module Using turtle.tracer(0) and update() Functions
Turtle Walk Animation

Animation Using Screen Events

The Pygame Events and Tkinter Widgets pages explained how the keyboard and mouse events are handled by the program to create the GUI.  We learned that it is necessary to bind the event to the event handler to enable the program to interact with a graphical object using keyboard keys or mouse.

The event handler method (function) takes the desired actions in response to events (mouse clicks of key press).  The user’s keypad presses and the mouse clicks are called Screen Events. To animate the turtle using the screen events, we will use the following Turtle module’s functions. These functions were discussed on Turtle Functions page.

Turtle Functions for Screen Events

turtle.onkey(fun,key)

The turtle module has a function turtle.onkey(fun,key) that binds the event handler function to the key event, such as key presses.  The event handler function ‘fun’ is a user-defined function. This function is written as part of the program using a def statement.  The onkey() function binds (associates) the function fun to the key (the key press event such as the left-arrow key, etc.).

Example: screen.onkey(next_frame, ‘Up’)

The above statement will call the function “next_frame” and associate the “next_frame” function with the up-arrow key.

turtle.listen()

In addition to binding the key press event to the event handler function, we need to ensure that the program listens to the key presses. Turtle module function turtle.listen() enables the program to listen to the key presses.

screen.listen()
window.ontimer(fun, time)

The Screen object function window.ontimer(fun,time) allows the function fun to be executed some specified time later.

Example: screen.ontimer(next_frame,10)

The above statement will call a function called “next_frame” 10 milliseconds later.

Now we will write a simple program to move an image as the user presses the left-arrow, right-arrow, up-arrow, and down-arrow keys.

The program uses the turtle.onkey(funkey) and turtle.listen() functions.

Note that turtle module recognizes the strings ‘Left’, ‘Right’, ‘Up’, and ‘Down’ as the respective arrow keys.

PROGRAM EXAMPLE: ANIMATION WITH SCREEN EVENTS – KEY PRESSES

Program name: turtle_keypress_move.py

1  # Turtle Animation using Screen Events - Arrow Keys.
2  import turtle
3  screen = turtle.Screen()
4  screen.setup(320,320)   # Set screen size.
5  screen.tracer(0) # Stop animation until frame is completed.
6  screen.title('TURTLE ANIMATION USING ARROW KEYS')
7  trtl = turtle.Turtle()
8  trtl.hideturtle() # We do not want to see the turtle image on the screen.
9  
10  # Initialize variables.
11  x, y, x_step, y_step = 0, 0, 10, 10  # Initialize global variables.
12  
13  def next_frame():
14      trtl.clear()   # Clear the screen before each next frame.
15      # x-step and y_step are the pexels the image moves at each key press.
16      trtl.penup()
17      trtl.goto(x, y)
18      trtl.pendown()
19      trtl.dot(20)  # Draw a black dot of radius = 20
20      screen.ontimer(next_frame, 10) # Call next_frame 10 msec later
21      screen.update()
22  
23  ###### DEFINE KEY PRESS EVENT HANDLER FUNCTIONS ######
24  def move_left():
25      global x
26      print('left arrow key pressed')
27      x = x - x_step
28  
29  def move_right():
30      global x
31      print('right arrow key pressed')
32      x = x + x_step
33  
34  def move_down():
35      global  y
36      print('down arrow key pressed')
37      y = y - y_step
38  
39  def move_up():
40      global y
41      print('up arrow key pressed')
42      y = y + y_step
43  
44  ###### BIND EVENTS TO THE FOUR ARROW KEYS  ######
45  screen.onkey(move_left, 'Left')  # Left arrow key bind to handler 'move_left'.
46  screen.onkey(move_right, 'Right')
47  screen.onkey(move_down, 'Down')
48  screen.onkey(move_up, 'Up')
49  
50  ######  CALL next-frame() FUNCTION ######
51  next_frame()
52  screen.listen()  # Check if key is pressed
53  screen.mainloop()

Detailed Line-by-line Explanation of the Program:

Lines 1) through 7): These are the same as in the previous program.

Line 8: trtl.hideturtle()

Hide the turtle so that it is not visible on the screen.

Line 11: x, y, x_step, y_step = 0, 0, 10, 10

Define the variables x and y as the coordinates of the turtle position. Also, define x_step and y_step as the number of pixels the turtle moves each time the user presses the key. Initialize these variables.

Line 13: def next_frame():

Define the functionality of the User-Defined Function next_frame().

Draw the image of a Dot

Line 19: trtl.dot(20)

Draw a black dot of radius = 20. This is the dot that will move across the screen as the user presses the keys.

Line 20: screen.ontimer(next_frame, 10)

Call the next_frame function 10 msec later.

Line 24: def move_left():

Define user Defined-Function move_left().

27: x = x – x_step

Subtract the x_step value from x (the current position of the turtle) when the left-arrow key is pressed by the user.

Lines 45 through 48: Bind the events toi the arrow keys.

Line 52: screen.listen()

Check if any arrow key is pressed.

Copyright © 2019 – 2021 softwareprogramming4kids.com

All Rights Reserved

Verified by MonsterInsights