Python Tkinter随机生成颜色?

时间:2017-10-21 15:21:04

标签: python tkinter colors fill

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")

嗨!我正在玩tkinter并生成随机三角形。问题是: 我想在fill =“”上使用random来生成随机颜色

random.randint(start,end)返回数字,但fill只接受字符串 fill =“red”或hexadecimal =“#RGB” 如果我输入像fill =(1,1,0)这样的数值估算器,它就不起作用。我怎么能在fill中生成随机字符串值?

谢谢

2 个答案:

答案 0 :(得分:1)

只需使用已知颜色列表中的tableView.reloadData()即可。你可以找到枚举的{python tkinter颜色图表here。然后,您可以随机选择 fill outline 值:

random.sample()

Tk Window Output 1 Tk Window Output 2 Tk Window Output 3

当然,如果你想重现相同的随机生成数字,总是播种:

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])

答案 1 :(得分:0)

在替代方案中,只需生成随机颜色并对其进行格式化:

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()