【问题标题】:Python Tkinter random generating the colors?Python Tkinter 随机生成颜色?
【发布时间】:2018-04-02 13:14:43
【问题描述】:
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 只接受像这样的字符串 填充=“红色”或十六进制=“#RGB” 如果我输入一个像 fill = (1,1,0) 这样的数值器,它就不起作用。如何在填充中生成随机字符串值?

谢谢

【问题讨论】:

  • 你不能把一大堆颜色字符串放在一个列表中,然后从列表中随机选择一个吗?

标签: python tkinter colors fill


【解决方案1】:

只需使用已知颜色列表中的random.sample()。您可以找到枚举here 的python tkinter 颜色图表。然后,您可以随机化 filloutline 值:

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

当然,如果您想重现完全相同的随机生成数字,请始终播种:

random.seed(444)   # WHERE 444 IS ANY INTEGER

【讨论】:

    【解决方案2】:

    或者,只需生成您的随机颜色并格式化它:

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

    【讨论】:

      猜你喜欢
      • 2016-07-17
      • 1970-01-01
      • 2015-06-15
      • 1970-01-01
      • 2015-11-07
      • 2012-02-19
      • 2013-04-02
      • 2016-02-20
      • 2013-12-31
      相关资源
      最近更新 更多