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

2024-10-01 02:38:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在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: bad color sequence: (236, 197, 141)

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

nt.colormode(255)

现在它告诉我这个错误

AttributeError: 'Turtle' object has no attribute 'colormode'

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


Tags: theinforsiterandomheadcolorturtle
1条回答
网友
1楼 · 发布于 2024-10-01 02:38:09

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

相关问题 更多 >