“AttributeError:'Turtle'对象没有属性'colormode'”,尽管Turtle.py的colormode atttribute

时间:2016-04-16 19:22:44

标签: python error-handling attributes

我尝试在this site上运行使用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.TurtleGraphicsError:颜色序列错误:(236,197,141)

然后,基于another site上的这个答案,我在“nt.color(......)”之前添加了这一行

  

nt.colormode(255)

现在它向我显示了这个错误

  

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

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

1 个答案:

答案 0 :(得分:3)

问题是您的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