【问题标题】:Error using turtle under Python 2.7 Idle在 Python 2.7 Idle 下使用 turtle 时出错
【发布时间】:2018-04-19 14:07:46
【问题描述】:
为什么我的代码在 turtle() 中显示错误?我正在使用 Python 2.7.13 空闲。该查询是关于使用海龟绘制一个正方形:
import turtle
def draw_square():
window=turtle.Screen()
window.bgcolor("red")
brad= turtle.Turtle()
brad.shape("yellow") # move forward
brad.speed(2)# turn pen right 90 degrees
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
window.exitonclick()
draw_square()
【问题讨论】:
标签:
python-2.7
turtle-graphics
【解决方案1】:
您在程序中犯了几个错误。首先,window.exitonclick() 没有正确缩进,因此您从函数外部引用了 draw_square() 的局部变量。您的狭窄的一个空格缩进可能是导致此问题的原因。
下一个错误是brad.shape("yellow"),因为黄色不是形状,而是颜色。此外,draw_square() 中的 cmets 似乎在错误的行上。有些人可能不认为这是一个错误,但我认为。
您的代码已重新编写以修复上述问题,并以更合乎逻辑的方式进行海龟编程:
import turtle
def draw_square(a_turtle):
a_turtle.forward(100) # move forward
a_turtle.right(90) # turn pen right 90 degrees
a_turtle.forward(100)
a_turtle.right(90)
a_turtle.forward(100)
a_turtle.right(90)
a_turtle.forward(100)
a_turtle.right(90)
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
brad.speed("slow")
draw_square(brad)
turtle.mainloop()