3

I need to generate a random color using r g b values to fill in these rectangles for a python school assignment, I'm getting a bad color sequence error even though I'm fairly sure I'm formatting it just as the Python documentation suggests.

r = random.randrange(0, 257, 10)
g = random.randrange(0, 257, 10)
b = random.randrange(0, 257, 10)


def drawRectangle(t, w, h):
    t.setx(random.randrange(-300, 300))
    t.sety(random.randrange(-250, 250))
    t.color(r, g, b)
    t.begin_fill()
    for i in range(2):
        t.forward(w)
        t.right(90)
        t.forward(h)
        t.right(90)
    t.end_fill()
    t.penup()

I'm quite confused as to why t.color(r, g, b) is not producing a random color?

3 Answers 3

4

turtle.colormode needs to be set to 255 to give color strings in Hex Code or R G B.

adding

screen.colormode(255)

no longer returned an error.

Sign up to request clarification or add additional context in comments.

Comments

1

Your variables r g and b are not global. You either have to add a global declaration at the top of your function or add them as parameters.

def my_function(r, g, b):
    # some stuff

Or...

def myfunction():
    global r, g, b
    # some stuff

6 Comments

How would I go about adding them as parameters?
In drawRectangle, you already have parameters: t, w and h. Just add them to that list in between the brackets. :)
Thanks, the global variables makes sense now, but I'm still getting an incorrect color sequence error, even if I just put in integers for r, b, b. t.color(100, 150, 200) still returns a bad color sequence error, is some other formatting wrong?
The error wouldn't be with the globals then. There could be something wrong with the colours themselves. I don't work with colours or turtle or anything, but that's the impression I get.
Thanks for your help as it did give me a better understanding of variables and parameters, but my problem lied in turtle.colormode which I outlined in my answer below.
|
0
import turtle as t 
import random

timmy = t.Turtle()
t.colormode(255)


def random_color():
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    random_color = (r, g, b)
    return random_color


timmy.color(random_color())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.