在 Python 中生成随机十六进制颜色 [英] Generating a Random Hex Color in Python

查看:48
本文介绍了在 Python 中生成随机十六进制颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个 Django 应用程序,每个成员"都被分配了一种颜色来帮助识别他们.它们的颜色存储在数据库中,然后在需要时打印/复制到 HTML 中.唯一的问题是我不确定如何在 python/django 中生成随机的 Hex 颜色.生成 RGB 颜色很容易,但是要存储它们,我需要 a) 在我的成员"模型中创建三个额外的列,或者 b) 将它们全部存储在同一列中并使用逗号将它们分开,然后,稍后,解析 HTML 的颜色.这些都不是很吸引人,所以,再次,我想知道如何在 python/django 中生成随机 Hex 颜色.

For a Django App, each "member" is assigned a color to help identify them. Their color is stored in the database and then printed/copied into the HTML when it is needed. The only issue is that I am unsure how to generate random Hex colors in python/django. It's easy enough to generate RGB colors, but to store them I would either need to a) make three extra columns in my "Member" model or b) store them all in the same column and use commas to separate them, then, later, parse the colors for the HTML. Neither of these are very appealing, so, again, I'm wondering how to generate random Hex colors in python/django.

推荐答案

import random
r = lambda: random.randint(0,255)
print('#%02X%02X%02X' % (r(),r(),r()))

这篇关于在 Python 中生成随机十六进制颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆