Python Tkinter Random Generating The Colors?
from tkinter import * import random tk = Tk() canvas = Canvas(tk, width=400, height=400) canvas.pack() for x in range(0, 40): x1 = random.randint(0,400) y1 = random.rand
Solution 1:
Simply use random.sample()
from a known list of colors. And you can find the python tkinter color chart enumerated here. You can then randomize for both fill and outline values:
COLORS = ['snow', 'ghost white', 'white smoke', 'gainsboro', 'floral white', 'old lace' ...]
for x in range(0, 40):
x1 = random.randint(0,400)
y1 = random.randint(0,400)
x2 = random.randint(0,400)
y2 = random.randint(0,400)
x3 = random.randint(0,400)
y3 = random.randint(0,400)
my_triangle = canvas.create_polygon(x1, y1, x2, y2, x3, y3,\
fill = (random.sample(COLORS, 1)[0]),
outline = random.sample(COLORS, 1)[0])
Of course, always seed if you want to reproduce same exact random generated numbers:
random.seed(444) # WHERE 444 IS ANY INTEGER
Solution 2:
In alternative just generate your random color and format it:
from tkinter import *
import random
def random_color():
return random.randint(0,0x1000000)
tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()
for x in range(0, 40):
color = '{:06x}'.format(random_color())
x1 = random.randint(0,400)
y1 = random.randint(0,400)
x2 = random.randint(0,400)
y2 = random.randint(0,400)
x3 = random.randint(0,400)
y3 = random.randint(0,400)
my_triangle = canvas.create_polygon(x1, y1, x2, y2, x3, y3,\
fill =('#'+ color), outline="red")
tk.mainloop()
Post a Comment for "Python Tkinter Random Generating The Colors?"