"AttributeError: 'Turtle' object has no attribute 'colormode'" despite Turtle.py having colormode atttribute

Question:

I tried running the code that uses the Turtle library on this site, shown here,

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()

in my own Python editor and I got this error:

turtle.TurtleGraphicsError: bad color sequence: (236, 197, 141)

Then, based on this answer on another site, I added in this line before “nt.color(……)”

nt.colormode(255)

Now it’s showing me this error

AttributeError: ‘Turtle’ object has no attribute ‘colormode’

Okay, so I checked my Python library and looked into the contents of Turtle.py. The colormode() attribute is definitely there. What is making the code able to run on the original site but not on my own computer?

Asked By: deadalous

||

Answers:

The issue is that your Turtle object (nt) doesn’t have a colormode method. There is one in the turtle module itself though.

So you just need:

turtle.colormode(255) 

instead of

nt.colormode(255)

Edit: To try to clarify your question in the comment, suppose I create a module called test.py, with a function, and a class, ‘Test’:

# module test.py

def colormode():
    print("called colormode() function in module test")

class Test
    def __init__(self):
        pass

Now, I use this module:

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
Answered By: Gerrat

Screen class in turtle module has colormode() method.
You can call screen_object.colormode(255).
In your code it would be:

wn.colormode(255)
Answered By: Meera

The problem is that you need to set up the colormode() attribute = 255. The class to reference is Screen(), based on your code you referenced this code as wn = turtle.Screen(). In order for you to make your code work, just by adding the following line of code.

wn.colormode(255)

Answered By: Winter Morillo