Turtle无法启动-内核繁忙

时间:2019-06-30 20:14:14

标签: python turtle-graphics

我正在尝试绘制固定数量的具有随机宽度和颜色的垂直条纹系列。不幸的是,内核仍然很忙,乌龟没有吸收任何东西。

我正在使用Anaconda-Jupyter 我意识到自己已经很模糊了,但是我真的不知道如何解决这个问题。 非常感谢愿意花时间帮助的人!

import turtle
from turtle import *
import random

window = turtle.Screen()
window.colormode(255)
window.bgcolor("black")
turtle = turtle.Turtle()
turtle.speed(10)
turtle.penup()
turtle.shape("turtle")
turtle.goto(0,0)
#turtle.mode("standard")

def drawstripes(rgb, length, width):
    turtle.color(rgb)
    turtle.begin_fill()
    turtle.forward(length)
    turtle.left(90)
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.end_fill()

n = 20
length = 100
totalwidth = 40
widths = [random.uniform(0, totalwidth) for i in range(0, n)]
widths.sort()

turtle.goto(0,length)
turtle.setheading(270)

while turtle.xcor() <= totalwidth :  
    for width in widths :
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)
        rgb = (r, g, b)
        drawstripes(rgb, length, width)

如前所述,预期结果是一系列相邻的垂直条纹,其宽度和颜色从x = 0到x = 40px

1 个答案:

答案 0 :(得分:1)

下面是对代码的重做,以便可以在Python控制台上正常工作,看看它在Anaconda-Jupyter下是否对您更好:

from turtle import Screen, Turtle
from random import randint, uniform

n = 20
length = 100
totalwidth = 80

def drawstripe(rgb, length, width):
    turtle.color(rgb)
    turtle.begin_fill()
    turtle.forward(length)
    turtle.left(90)
    turtle.forward(width)
    turtle.left(90)
    turtle.forward(length)
    turtle.left(180)
    turtle.end_fill()

window = Screen()
window.colormode(255)
window.bgcolor("black")

turtle = Turtle()
turtle.shape('turtle')
turtle.speed('fastest')
turtle.penup()

widths = [uniform(0, totalwidth) for i in range(0, n)]
widths.sort()

turtle.sety(length)
turtle.setheading(270)

for width in widths:
    r = randint(0, 255)
    g = randint(0, 255)
    b = randint(0, 255)
    rgb = (r, g, b)
    drawstripe(rgb, length, width)

    if turtle.xcor() > totalwidth:
        break

turtle.hideturtle()
window.mainloop()

具体更改:在末尾添加了mainloop()调用;在drawstripe()中增加了最后一转,使乌龟前进而不是后退;提取了内部循环,因为不清楚外部循环试图达到什么目的-添加外部功能作为条件;将totalwidth加倍以使输出更加明显。

enter image description here