Cannot implement onkeyrelease()
from Python's turtle module. Please advise. Error message: 'module' object has no attribute 'onkeyrelease'
. Tried replacing turtle.onkeyrelease(stay, 'd')
with wn.onkeyrelease(stay, 'd')
to no avail.
import turtle
speed = 0
wn = turtle.Screen()
wn.tracer(0)
box = turtle.Turtle()
box.shape('square')
box.penup()
def move_right():
global speed
speed = 2
def stay():
global speed
speed = 0
turtle.listen()
turtle.onkey(move_right, 'd')
turtle.onkey(stay, 's')
turtle.onkeyrelease(stay, 'd')
while True:
wn.update()
box.setx(box.xcor() + speed)
My guess, based on the error message, is that you are running Python 2 and onkeyrelease()
is a Python 3 method. Even so:
An artifact of the transition from Python 2 to Python 3, onkey()
and onkeyrelease()
are synonyms . What you probably want is onkeypress()
and onkeyrelease()
. Even so:
That said, it's iffy whether trying to do different things on the key press and release is going to work. On my system, both press and release are triggered by a key press. Your results, due to OS perhaps, might vary.
You may be better off using two keys, 'd' to start the motion, 's' to stop it:
from turtle import Screen, Turtle, mainloop
speed = 0
def move_faster():
global speed
speed = 2
def stay():
global speed
speed = 0
def move():
box.forward(speed)
screen.update()
screen.ontimer(move)
screen = Screen()
screen.tracer(False)
box = Turtle()
box.shape('square')
box.penup()
screen.onkey(stay, 's')
screen.onkey(move_faster, 'd')
screen.listen()
move()
mainloop()
This code should work under Python 2 and Python 3.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.