简体   繁体   English

Python,乌龟不会出现,并且不会响应键盘控件

[英]Python, turtle won't appear and won't respond to keyboard controls

I'm trying to make a Python program where a player controls a turtle (from the 'turtle' module) to reach a goal, avoiding an obstacle along the way. 我正在尝试制作一个Python程序,让玩家控制“乌龟”(通过“乌龟”模块)以达到目标,并避免途中遇到障碍。

The code for the obstacle and goal drawing works fine, however for some reason the player turtle is not visible and will not respond to keyboard commands. 障碍物和目标绘图的代码可以正常工作,但是由于某些原因,玩家乌龟不可见并且无法响应键盘命令。 I've elected to not include the entire code and will instead include only the relevant sections. 我选择不包括整个代码,而仅包括相关部分。 Below is the code for the player controls. 下面是播放器控件的代码。 The player is setup as a turtle already and screen is setup with screen = turtle.Screen() . 播放器已设置为乌龟,并且屏幕已使用screen = turtle.Screen() I recieve no errors when I try to run it. 当我尝试运行它时,我没有收到任何错误。 I will leave the link to the code on my github if anyone would like to have a look at it. 如果有人想看一下,我会将链接保留在我的github上。

speed = 1


def travel():
    player.forward(speed)
    screen.ontimer(travel, 10)


player.pendown()
player.forward(10)
screen.onkey(lambda: player.setheading(90), 'Up')
screen.onkey(lambda: player.setheading(180), 'Left')
screen.onkey(lambda: player.setheading(0), 'Right')
screen.onkey(lambda: player.setheading(270), 'Down')

screen.listen()

travel()

screen.mainloop()

Once complete, your example works fine: 完成后,您的示例可以正常工作:

from turtle import Turtle, Screen

def travel():
    player.forward(1)
    screen.ontimer(travel, 10)

screen = Screen()
player = Turtle()

screen.onkey(lambda: player.setheading(0), 'Right')
screen.onkey(lambda: player.setheading(90), 'Up')
screen.onkey(lambda: player.setheading(180), 'Left')
screen.onkey(lambda: player.setheading(270), 'Down')

screen.listen()

travel()

screen.mainloop()

As far as your larger program goes, I recommend you comment out these lines: 至于您的大型程序,我建议您注释掉以下几行:

goal._tracer(0)
...
obstacle._tracer(0)

And your player turtle should show up. 并且您的player乌龟应该出现。 I suggest you not mess with tracer() until you've completed the bulk of your program and you understand what tracer() does. 我建议您在完成大部分程序并且了解tracer()功能之前,不要将tracer()弄乱。

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

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