Skip to main content

Section 5.5 Listener Functions

We have talked about interactivity: you have obtained input from the end user and you have shown the end user output by having turtles make fun animated drawings in a canvas window. Let’s take that interactivity a step further, now that we know about functions, and add a listener function to our turtle scripts.
First, let’s consider this turtle drawing example.
This example contains three different functions. First note how nicely modularized this code is, with each funtion doing one small thing: moving the turtle, giving the turtle a random colour, and drawing a random sized square. We call the three functions at the bottom of the script on lines 30-32. Note also that line 25 creates a random colour by generating 3 random values. Don’t worry about this for now - you will learn more about digital colours in a later section of this chapter.
If we wanted to draw more than one square, we could put a loop around lines 30-32, but that isn’t very interactive - it doesn’t involve the end user in any way. What if we want the user to decide when they have enough squares on the canvas? By adding a listener function, we can draw squares randomly in response to end user key presses. The version below does this, by adding a key_r function, and adding two lines of code at the bottom of the script to register the listener function and to start listening for window events such as keypresses.
Run the code below, click your cursor inside the canvas and then type the ’r’ key a few times to see it in action. Now the end user is in control!

Note 5.5.1.

The listener function only registers user inputs after clicking on the canvas.
Let’s add one more listener function to this script that ends the script. The version below adds a listener event for key_q that closes the canvas and ends the script.
Try it out yourself. Add two functions to the code below. Add a function that draws a triangle (just copy, paste and edit the square function to draw three sides, with a turning angle of 120 instead of 90). Then add a listener function that can be called in response to the end user typing ‘t’. Then add a line of code at the bottom of the script to tell the computer what function to call when the user types ‘t’.
There are a number of other events we can listen for and respond to, such as mouse clicks and drags, but we will return to those when we revisit functions with parameters in Chapter 9.

Note 5.5.2. Common Mistake with Listener Functions.

Most of the listener functions you write are functions that you should never invoke yourself. Notice that we never explicitly call key_r() in the scripts above. They are invoked automatically by the operating system. So, don’t call your own listener functions. Run your script, be the end user, and press the keys to test your listener methods!
Check your understanding

Checkpoint 5.5.3.

    How many times will the hello function get called?
    import turtle
    import random
    
    
    def hello():
        alex.penup()
        x = random.randrange(-200, 200) # get random x location
        y = random.randrange(-200, 200) # get random y location
        alex.goto(x, y)
        alex.pendown()
        alex.write("Hello!")
    
    wn = turtle.Screen()      # Set up the window and its attributes
    alex = turtle.Turtle()    # create alex
    
    alex.forward(20)
    
    wn.onkey(hello, 'h')
    wn.listen()
    
  • 0
  • It is possible that it is never invoked, but it could be invoked
  • 1
  • This function gets called in response to end user input
  • It doesn’t - there is an error in the code
  • No, there are no errors
  • It depends on the end user
  • Yes, every time the user presses the h key, the hello function will execute
  • At least once
  • If the user never presses ’h’, this function never executes

Checkpoint 5.5.4.

    How many times will the goodbye() function get called?
    import turtle
    import random
    
    def hello():
        alex.penup()
        x = random.randrange(-200, 200) # get random x location
        y = random.randrange(-200, 200) # get random y location
        alex.goto(x, y)
        alex.pendown()
        alex.write("Hello!")
    
    def goodbye():
        alex.penup()
        x = random.randrange(-200, 200) # get random x location
        y = random.randrange(-200, 200) # get random y location
        alex.goto(x, y)
        alex.pendown()
        alex.write("Goodbye!")
    
    wn = turtle.Screen()      # Set up the window and its attributes
    alex = turtle.Turtle()    # create alex
    
    alex.forward(20)
    
    wn.onkey(hello, 'h')
    wn.listen()
    
  • At least once
  • No, there are no calls to the goodbye() function
  • 1
  • No, there are no calls to the goodbye() function
  • It doesn’t - there is an error in the code
  • Yes, there is a logic error because the goodbye() function is not invoked or registered as a listener function
  • It depends on the end user
  • No, it is not registered as a listener function

Checkpoint 5.5.5.

    How many times will the goodbye() function get called?
    import turtle
    import random
    
    def hello():
        alex.penup()
        x = random.randrange(-200, 200) # get random x location
        y = random.randrange(-200, 200) # get random y location
        alex.goto(x, y)
        alex.pendown()
        alex.write("Hello!")
    
    def goodbye():
        alex.penup()
        x = random.randrange(-200, 200) # get random x location
        y = random.randrange(-200, 200) # get random y location
        alex.goto(x, y)
        alex.pendown()
        alex.write("Goodbye!")
    
    wn = turtle.Screen()      # Set up the window and its attributes
    alex = turtle.Turtle()    # create alex
    
    alex.forward(20)
    
    wn.onkey(hello, 'h')
    wn.onkey(goodbye, 'b')
    
  • At least once
  • No, there are no calls to the goodbye() function
  • It doesn’t - there is an error in the code
  • Yes, there is a logic error because there is no listen() function telling the operating system to listen for window events
  • 1
  • No, there are no calls to the goodbye() function
  • It depends on the end user
  • No, there are no calls to the goodbye() function
You have attempted of activities on this page.