简体   繁体   English

海龟图形 onkeyrelease()

[英]Turtle graphics onkeyrelease()

Cannot implement onkeyrelease() from Python's turtle module.无法从 Python 的 turtle 模块实现onkeyrelease() Please advise.请指教。 Error message: 'module' object has no attribute 'onkeyrelease' .错误消息: 'module' object has no attribute 'onkeyrelease' Tried replacing turtle.onkeyrelease(stay, 'd') with wn.onkeyrelease(stay, 'd') to no avail.尝试用turtle.onkeyrelease(stay, 'd')替换wn.onkeyrelease(stay, 'd')无济于事。

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.根据错误消息,我的猜测是您正在运行 Python 2 并且onkeyrelease()是 Python 3 方法。 Even so:即使是这样:

An artifact of the transition from Python 2 to Python 3, onkey() and onkeyrelease() are synonyms .从 Python 2 到 Python 3 的过渡产物,onkey onkey()onkeyrelease()同义词 What you probably want is onkeypress() and onkeyrelease() .您可能想要的是onkeypress()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:您最好使用两个键,'d' 开始动作,'s' 停止它:

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.此代码应在 Python 2 和 Python 3 下工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM