"AttributeError: 'Turtle' object has no attribute 'colormode'"尽管 Turtle.py 有色模特征



我试着在这个网站上运行使用Turtle库的代码,如图所示,

import turtle
import random
def main():
    tList = []
    head = 0
    numTurtles = 10
    wn = turtle.Screen()
    wn.setup(500,500)
    for i in range(numTurtles):
        nt = turtle.Turtle()   # Make a new turtle, initialize values
        nt.setheading(head)
        nt.pensize(2)
        nt.color(random.randrange(256),random.randrange(256),random.randrange(256))
        nt.speed(10)
        wn.tracer(30,0)
        tList.append(nt)       # Add the new turtle to the list
        head = head + 360/numTurtles
    for i in range(100):
        moveTurtles(tList,15,i)
    w = tList[0]
    w.up()
    w.goto(0,40)
    w.write("How to Think Like a ",True,"center","40pt Bold")
    w.goto(0,-35)
    w.write("Computer Scientist",True,"center","40pt Bold")
def moveTurtles(turtleList,dist,angle):
    for turtle in turtleList:   # Make every turtle on the list do the same actions.
        turtle.forward(dist)
        turtle.right(angle)
main()

在我自己的Python编辑器中,我得到了这个错误:

turtle.TurtleGraphics错误:错误的颜色序列:(236197141)

然后,根据另一个网站上的这个答案,我在"nt.color(……)"之前的这一行添加了

nt.彩色模式(255)

现在它显示给我这个错误

AttributeError:"Turtle"对象没有属性"colormode"

好吧,所以我检查了我的Python库,并查看了Turtle.py的内容。colormode()属性肯定在那里。是什么让代码能够在原始网站上运行,但不能在我自己的电脑上运行?

问题是Turtle对象(nt)没有colormode方法。不过,海龟舱本身就有一个。

所以你只需要:

turtle.colormode(255) 

而不是

nt.colormode(255)

编辑:为了在评论中澄清您的问题,假设我创建了一个名为test.py的模块,其中包含一个函数和一个类"Test":

# module test.py
def colormode():
    print("called colormode() function in module test")
class Test
    def __init__(self):
        pass

现在,我使用这个模块:

import test
nt = test.Test()  # created an instance of this class (like `turtle.Turtle()`)
# nt.colormode()  # won't work, since `colormode` isn't a method in the `Test` class
test.colormode()  # works, since `colormode` is defined directly in the `test` module

海龟模块中的Screen类具有colormode()方法。您可以拨打screen_object.colormode(255)。在您的代码中,它将是:

wn.colormode(255)

问题是需要设置colormode()属性=255。要引用的类是Screen(),基于您的代码,您将此代码引用为wn=turtle。屏幕()。为了让您的代码正常工作,只需添加以下代码行即可。

wn.colormode(255)

最新更新