Shlappas
Shlappas

Reputation: 31

Random fill colour for shapes in Python(TKinter)

I am wondering how to get a random color out of a list to use in the draw_rectangle()

colors = ["red", "orange", "yellow", "green", "blue", "violet"]

canvas.create_rectangle(self.x, self.y, self.x + 60, self.y + 60, fill = random.choice(colors))

This causes my code to crash, what else can I try?

Upvotes: 2

Views: 23689

Answers (4)

George
George

Reputation: 11

Also I do this way:

color = f'#{random.randrange(256**3):06x}'

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239443

You can use random.choice like this

import random
colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
canvas.create_rectangle(self.x, self.y, self.x + 60, self.y + 60, fill = random.choice(colors))

This will pass a random color to fill whenever this code is executed.

Upvotes: 3

Mamazur
Mamazur

Reputation: 179

de=("%02x"%random.randint(0,255))
re=("%02x"%random.randint(0,255))
we=("%02x"%random.randint(0,255))
ge="#"
color=ge+de+re+we

and in tkinter put

fill=color

easy you can also make

fill="#"+("%06x"%random.randint(0,16777215))

Upvotes: 5

Amaury Medeiros
Amaury Medeiros

Reputation: 2233

You can use choice, from package random

random.choice(color)

Upvotes: -1

Related Questions