问题
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.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 =("blue"), outline="red")
Hi! I am playing with tkinter and generating random triangles. The problem is: I want to use random on fill = " " to generate random colors
random.randint(start, end) returns numbers, but fill accepts only strings like fill ="red" or hexadecimal = "#RGB" if I enter a numeric valuer like fill = (1,1,0) it doesn't work. How could I generate random string values in fill?
Thank you
回答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
回答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()
来源:https://stackoverflow.com/questions/46864799/python-tkinter-random-generating-the-colors