You will need to know how to use functions in order to understand this section.
Using Events with Turtle
What do we do when we want to control a turtle with our mouse or keyboard? These are called events, which you'll learn about here.
You will need to know how to use functions in order to understand this section.
What do we do when we want to control a turtle with our mouse or keyboard? These are called events, which you'll learn about here.
Controlling our turtle with a keyboard is easy. We begin by creating a function that takes NO parameters:
def up():
t.forward(10)
We then write s.onkey(functionName,"key"):
def up():
t.forward(10)
s.onkey(up,"Up")
Almost done! Add a s.listen() to the code:
def up():
t.forward(10)
s.onkey(up,"Up")
s.listen()
Done!
We can make a program that moves the turtle with the arrow keys like so:
from turtle import *
t = Turtle()
s = Screen()
def up():
t.seth(90)
t.forward(10)
def down():
t.seth(270)
t.forward(10)
def left():
t.seth(180)
t.forward(10)
def right():
t.seth(0)
t.forward(10)
s.onkey(up,"Up")
s.onkey(down,"Down")
s.onkey(left,"Left")
s.onkey(right,"Right")
s.listen()
Remember, we only need to call s.listen() once in our program.
Creating click events with turtle is even easier. Here's how to make a click event:
def func(x,y):
code...
s.onclick(func)
Of course, we also need the s.listen() somewhere in the code.
For example, to make the turtle go to wherever we click we can use:
from turtle import *
t = Turtle()
s = Screen()
def move(x,y):
t.up()
t.goto(x,y)
t.down()
s.onclick(move)
s.listen()
Creating a drag event is like a click event, only we call it on the turtle. Here's how:
def func(x,y):
code...
t.ondrag(func)
For example, to make the turtle draw when we drag it, use:
from turtle import *
t = Turtle()
s = Screen()
def draw(x,y):
t.down()
t.goto(x,y)
t.ondrag(draw)
s.listen()
Create a program that changes the background color to a random color when you click the background.
Adjust your previous program so that you can go forward with the up key, and turn left or right 30 degrees with the left and right keys.
Adjust your previous program to move your turtle where you drag it, when you drag it, without drawing.
Events: In programming, an event is something that the user does. For example, pressing the r key, clicking the mouse, and moving the mouse are all events.
Right-click events
t.onclick()
Adjust your previous program so that it changes the background to black when you right-click it.
Adjust your previous program so that it changes the turtle's color to a random color when you click it.