Acciones - johncroth/pythonEd2024 GitHub Wiki

Sometimes we want our program to take a particular action when something happens. For example, when a user presses a key, when a timer expires, or (more advanced) when an email arrives. The way modern languages like Python do this is to express the action as a function, and then hand that function to a listener, which is another part of a program that waits for events to occur.

With turtle this is pretty easy, but it can be tricky because there is a common mistake that is hard to find.

To start, save and execute the following in the file accion_a.py. While the programming is running, press the m key to move the turtle, and press the i key to print a message to the console.

from turtle import *
from random import *

def imprimir_hola():
    print( "Hola" )

def mover_al_aleatorio():
    right( randint( 0, 360))
    forward(40)

onkey( imprimir_hola, "i")
onkey( mover_al_aleatorio, "m" )
listen()

First, we define two functions imprimir_hola and mover_al_aleatorio that represent two actions. Then with onkey( imprimir_hola, "i") (roughly "con tecla") we tell python to do imprimir_hola() when the i key is pressed. In the next line, we tell Python to domover_al_aleatorio() when the m key is pressed.

Finally, the listen() "escuchar" function tell Python to start listening for these key presses.

Warning

Now, change the line onkey( imprimir_hola, "i") to onkey( imprimir_hola(), "i") and execute the program again. Note three things: (1) Python does not complain about any errors, and everything looks ok, (2) pressing the i key now does nothing, although the m key works as before, (3) The "Hola" message is printed once.

Avoid this mistake, because it is frustrating and hard to find. It's hard to explain the difference, which is subtle: The expression imprimir_hola is the definition of the action, waiting to be taken, while imprimir_hola() is the result of taking the action once, which just prints "Hola" once. (Honestly, the turtle package should treat this is as an error, but as programmers we often have to live with this sort of thing.)

Ejercicios

Omit "listen()"

Assign the same action to different keys.

Assign left, right, and forward to specific keys for a drawing program. Add a "backward" action and assign it to a key. Add something to change the color randomly. Add buttons to raise and lower the pen.

Introduce

ontimer( action, t)