Sajjad Ahmadi
Sajjad Ahmadi

Reputation: 19

write a code to make random colors on object

I tried to write a code with pyhton on tkinter.

def random_color():
hashtag = str('#')
eka_väri = random.choice(range(0,255))
toka_väri = random.choice(range(0, 256))
kolmas_väri = random.choice(range(0,256))
red = hex(eka_väri)
green = hex(toka_väri)
blue = hex(kolmas_väri)
gbl= [red[2:], green[2:], blue[2:]]
yhdistäjä = ''
x = yhdistäjä.join(gbl)
return (hashtag + x)

that code make RGB numbers to a hex number. its works like this.

canvas.create_polygon(10, 10, 10, 60, 50, 35, fill=random_color)

when I put it like this it doesnt work anymore.

def random_triangle():
p1 = random.randrange(w)
p2 = random.randrange(h)
p3 = random.randrange(w)
p4 = random.randrange(h)
p5 = random.randrange(w)
p6 = random.randrange(h)
Canvas.create_polygon(p1, p2, p3, p4, p5, p6, fill=random_color, outline=random_color)

can someone tell me why?

Upvotes: 0

Views: 452

Answers (1)

Minh Quang Nguyen
Minh Quang Nguyen

Reputation: 345

The fill and outline parameter must be function. This will work:

import random
from tkinter import *

def random_color():
    hashtag = str('#')
    eka_väri = random.choice(range(0,255))
    toka_väri = random.choice(range(0, 256))
    kolmas_väri = random.choice(range(0,256))
    red = hex(eka_väri)
    green = hex(toka_väri)
    blue = hex(kolmas_väri)
    gbl= [red[2:], green[2:], blue[2:]]
    yhdistäjä = ''
    x = yhdistäjä.join(gbl)
    return (hashtag + x)

def random_triangle():
    w = 500
    h = 500
    p1 = random.randrange(w)
    p2 = random.randrange(h)
    p3 = random.randrange(w)
    p4 = random.randrange(h)
    p5 = random.randrange(w)
    p6 = random.randrange(h)
    Canvas.create_polygon(p1, p2, p3, p4, p5, p6, fill=random_color(), outline=random_color())
root = Tk()
Canvas = Canvas()
Canvas.pack()
random_triangle()
root.mainloop()

Your random_color() function is will also be error for some cases when the return hex code is not in right format. Instead of using rgb, you can use hex code like this:

def random_color():
    return "#" + ''.join([random.choice('0123456789ABCDEF') for j in range(6)])

Upvotes: 1

Related Questions