首页 > 解决方案 > 属性错误:部分初始化的模块 'turtle' 没有属性 'bgcolor'

问题描述

当我使用海龟时,无论我收到此错误消息:

File "[REDACTED FOR SECURITY]", line 1, in <module>
    from turtle import *
  File "[REDACTED FOR SECURITY]", line 5, in <module>
    turtle.bgcolor('black')
AttributeError: partially initialized module 'turtle' has no attribute 'bgcolor' (most likely due to a circular import)

我什至没有使用turtle.bgcolor().

这是我的代码,用于绘制蕨类植物:

from turtle import *
import random

pen = turtle.Turtle()
pen.speed(15)
pen.color("blue")
pen.penup()

x = 0
y = 0
for n in range(110000):
    pen.goto(65 * x, 37 * y - 252)  # 57 is to scale the fern and -275 is to start the drawing from the bottom.
    pen.pendown()
    pen.dot()
    pen.penup()
    r = random.random()  # to get probability
    r = r * 100
    xn = x
    yn = y
    if r < 1:  # elif ladder based on the probability
        x = 0
        y = 0.16 * yn
    elif r < 86:
        x = 0.85 * xn + 0.04 * yn
        y = -0.04 * xn + 0.85 * yn + 1.6
    elif r < 93:
        x = 0.20 * xn - 0.26 * yn
        y = 0.23 * xn + 0.22 * yn + 1.6
    else:
        x = -0.15 * xn + 0.28 * yn
        y = 0.26 * xn + 0.24 * yn + 0.44

标签: pythonpython-3.8python-turtle

解决方案


正如this answer中所指出的,您需要导入turtle模块本身,而不是只导入其所有属性:

import turtle

你的原因是因为你有

pen = turtle.Turtle()

如果您不这样做import turtle,则turtle不会定义该行中的。


我想解决的一件事是,您不需要关闭海龟笔以使该turtle.dot()方法起作用,从而减少

    pen.pendown()
    pen.dot()
    pen.penup()

    pen.dot()

将有效提高您程序的效率。


推荐阅读