Skip to main content

Section 8.12 Listener Functions with Parameters

Recall that in Chapter 6 we learned about adding interactivity to programs by adding listener functions that can respond to user events. The script below draws one random square, and then allows more squares to be drawn whenever the user presses the r key. The key_r function is a listener function that only gets called when the operating system detects that the r key is pressed by the user, while the turtle window is listening (note the statement on line X that tells the operating system to listen for events on this turtle graphics window).
Now that we know about function parameters, we can revisit these listener functions and make use of other types of user events. What if we want the user to define not just when to add a square, but where to add a square? We can register a listener function that will listen for mouse click events. The reason we need parameters is that the operating system, when passing a mouse click event to Python, will pass along x and y coordinates of where in the turtle window the click happened. Those coordinates will be stored in x and y parameters. The script below is a modification of the one above that adds a mouse click listener.
Try this out yourself in the script below. The script registers four listener functions. Two are already complete. Complete the other two functions, as specified in the comments.
Check your understanding

Checkpoint 8.12.1.

    Where does the message get written on canvas?
    import turtle
    import random
    
    
    def here(x, y):
        alex.penup()
        alex.goto(x, y)
        alex.pendown()
        alex.write("You are here!")
    
    wn = turtle.Screen()      # Set up the window and its attributes
    alex = turtle.Turtle()    # create alex
    alex.goto(100, 100)
    
    wn.onclick(here)
    wn.listen()
    
  • center of the canvas
  • It is possible that it is drawn there, if that’s where the user clicks
  • 100, 100
  • It is possible that it is drawn there, if that’s where the user clicks
  • It doesn’t - the ’here’ function is never called
  • The message is in a listener function
  • It depends on where the end user clicks
  • Yes, because the code displaying the message is in a listener function that is called when the user clicks on the canvas
You have attempted of activities on this page.