Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Random Color Generation using Turtle

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?

like image 795
Rial Johnson Avatar asked Jun 23 '26 11:06

Rial Johnson


2 Answers

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.

like image 161
Rial Johnson Avatar answered Jun 26 '26 00:06

Rial Johnson


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
like image 34
Zizouz212 Avatar answered Jun 26 '26 02:06

Zizouz212



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!