简体   繁体   English

检测 Python 中 Turtle 模块中的按键

[英]Detecting Keypresses in the Turtle module in Python

I want it so my Up key moves the turtle and my S key cleans the screen.我想要它,所以我的向上键移动乌龟,我的 S 键清洁屏幕。 Also, the up key command works:此外,向上键命令有效:

import turtle
from turtle import Turtle, Screen

screen = Screen()

jack = Turtle("turtle")
jack.color("red", "green")
jack.pensize(10)
jack.speed(0)

def clean(x,y):
    jack.clear()
def move():
    jack.forward(100)

turtle.listen()
turtle.onkey(clean,"S")
turtle.onkey(move,"Up")

screen.mainloop()

@jasonharper is correct about the capitalization issue (+1) but you clearly have other issues with this code as you import turtle two different ways. @jasonharper 关于大写问题(+1)是正确的,但是当您以两种不同的方式导入海龟时,您显然还有其他问题。 Ie you're mixing turtle's object-oriented API with its functional API.即,您将海龟的面向对象的API 与其功能API 混合在一起。 Let's rewrite the code to just use the object-oriented API:让我们重写代码以仅使用面向对象的 API:

from turtle import Screen, Turtle

def move():
    turtle.forward(100)

screen = Screen()

turtle = Turtle('turtle')
turtle.color('red', 'green')
turtle.pensize(10)
turtle.speed('fastest')

screen.onkey(turtle.clear, 's')
screen.onkey(move, 'Up')
screen.listen()

screen.mainloop()

I've changed variable names to make it clear which methods are screen instance methods and which are turtle instance methods.我更改了变量名称,以明确哪些方法是屏幕实例方法,哪些是海龟实例方法。 Your double import obscured this.您的双重导入掩盖了这一点。

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

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