我在 python 2.7 中用循环搞乱海龟导入,海龟不会移动

I'm messing around with the turtle import in python 2.7 with loops and the turtle won't move

我在 python 2.7 中用循环搞乱 turtle 导入,我只看到屏幕闪烁,程序退出。 这是我的代码:

import turtle

colors = ["red", "orange", "yellow", "green", "blue", "purple"]
dColors = dict(enumerate(colors))


def circleOfShapes(aTurtle):
    edges = 3
    radius = 100
    for i in range(5):
        for k in range(360 / 5):
            aTurtle.color(dColors.get(i))
            aTurtle.circle(radius, None, edges)
            aTurtle.right(5)
        edges += 1
        radius -= 10


turt = turtle.Turtle()
turt.shape("arrow")

window = turtle.Screen()
window.bgcolor("white")
window.exitonclick()

circleOfShapes(turt)

这只是我想为我的孩子做一些很酷的东西,让他在很小的时候就对编程产生兴趣,就像我希望的那样。感谢您的帮助。

对我来说,代码运行良好。唯一的问题是在您的 for 循环中,您试图在第 11 行中使用浮点数进行循环。您需要使用整数。你可以施放它。那应该解决它。希望这有帮助。

编辑:代码的另一个问题是 window.exitonclick()

删除或注释掉

这是在 Python 2 和 Python 3 上运行的代码的略微修改版本。

import turtle

colors = ["red", "orange", "yellow", "green", "blue", "purple"]
dColors = dict(enumerate(colors))

def circleOfShapes(aTurtle):
    edges = 3
    radius = 100
    for i in range(5):
        for k in range(360 // 5):
            aTurtle.color(dColors.get(i))
            aTurtle.circle(radius, None, edges)
            aTurtle.right(5)
        edges += 1
        radius -= 10

turt = turtle.Turtle()
turt.shape("arrow")
#turt.hideturtle()
#turt.speed(0)

window = turtle.Screen()
window.bgcolor("white")

circleOfShapes(turt)
window.exitonclick()

您可以通过取消注释 #turt.hideturtle() #turt.speed(0)

中的一个或两个来加快速度

我将您内部 range 调用中的除法更改为 360 // 5 以确保它 return 是一个整数。这使得代码与 Python 2 和 Python 3 更加兼容。

在Python 2中,/除法运算符将return一个int,如果它的操作数都是int,在Python 3 它总是return一个float。因此,当您需要 int 商时,最好使用 // 底除法运算符。

Python 2 range 将接受一个 float arg,但它会给出弃用警告。在 Python 3 中,它只会引发错误。