HomeTurtlegraficsGPanelRobotics WebTigerPython
 Python - Online
keyevents
Deutsch   English   

13. KEY EVENTS

 

 

YOU LEARN HERE...

 

how you can influence the program flow by pressing keyboard keys. Similar to the mouse events, you define in a callback function what should happen when a keyboard key is pressed. The callback function is not called by the program, but automatically by the system when a key is pressed.

 

 

EXAMPLES

 

Example 1: The Turtle draws a kick when any key is pressed

You define a callback function onKeyPressed(key) . This returns the name of the key pressed and calls thel step() function, which draws a step.

The callback function is registered via a parameter of makeTurtle(). This tells the system that it should call this function with every keyboard click.

 

Program:

from gturtle import *

def onKeyPressed(key):
    print(key)
    step()

def step():
    forward(20)
    right(90)
    forward(20)
    left(90)
    
makeTurtle(keyPressed = onKeyPressed)
addStatusBar(20)
setStatusText("Press any key!")
► Copy to clipboard

The name of the pressed key is displayed with print(key) in the output window. Also test the cursor keys. You will need their names in the next example.
 

 

Example 2: The Turtle is controlled with cursor keys.
The callback function onKeyPressed(key) onKeyPressed(key) returns the name of the pressed key. In an if-elif structure, you specify the direction of movement of the turtle. If one of the arrow keys is pressed, the Turtle changes direction and then moves a short distance forwards. To make the movement faster, select speed(-1).

 

Program:

from gturtle import *

def onKeyPressed(key):
    if key == "ArrowLeft":
        setHeading(-90)
    elif key == "ArrowRight":
        setHeading(90)
    elif key == "ArrowUp":
        setHeading(0)
    elif key == "ArrowDown":
        setHeading(180)
    forward(10)

makeTurtle(keyPressed = onKeyPressed)
speed(-1)
addStatusBar(20)
setStatusText("Use cursor keys to move me!")
► Copy to clipboard

 

 

REMEMBER...

 

is not called by your program, but by the system when you have pressed a key. You can display the name of the keys, in particular the special keys, in the output window with print(key).

The callback function is registered as a parameter of makeTurtle().

 

 

TO SOLVE BY YOURSELF

 

1.

When the “r” key is pressed, a red star should be drawn, the “g” key a green star and the “b” key a blue star.

 

 

2.
When any key is pressed, 1, 2, 3, 4, 5 or 6 filled circles appear at random.  

3.

You control a traffic light system with the “r”, “g” and “y” keys. When you press the “r” button, the red traffic light appears, with “g” the yellow one and with “g” the green one.