Generating a Random Hex Color in Python

前端 未结 15 1715
悲&欢浪女
悲&欢浪女 2020-11-29 01:36

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. T

相关标签:
15条回答
  • 2020-11-29 02:09

    little late to the party,

    import random
    chars = '0123456789ABCDEF'
    ['#'+''.join(sample(chars,6)) for i in range(N)]
    
    0 讨论(0)
  • 2020-11-29 02:09

    So many ways to do this, so here's a demo using "colorutils".

    pip install colorutils

    It is possible to generate random values in (RGB, HEX, WEB, YIQ, HSV).

    # docs and downloads at 
    # https://pypi.python.org/pypi/colorutils/
    
    from colorutils import random_web
    from tkinter import Tk, Button
    
    mgui = Tk()
    mgui.geometry('150x28+400+200')
    
    
    def rcolor():
        rn = random_web()
        print(rn)  # for terminal watchers
        cbutton.config(text=rn)
        mgui.config(bg=rn)
    
    
    cbutton = Button(text="Click", command=rcolor)
    cbutton.pack()
    
    mgui.mainloop()
    

    I certainly hope that was helpful.

    0 讨论(0)
  • 2020-11-29 02:11

    Basically, this will give you a hashtag, a randint that gets converted to hex, and a padding of zeroes.

    from random import randint
    color = '#{:06x}'.format(randint(0, 256**3))
    #Use the colors wherever you need!
    
    0 讨论(0)
  • 2020-11-29 02:13

    Would like to improve upon this solution as I found that it could generate color codes that have less than 6 characters. I also wanted to generate a function that would create a list that can be used else where such as for clustering in matplotlib.

    import random
    
    def get_random_hex:
        random_number = random.randint(0,16777215)
    
        # convert to hexadecimal
        hex_number = str(hex(random_number))
    
        # remove 0x and prepend '#'
        return'#'+ hex_number[2:]
    

    My proposal is :

    import numpy as np 
    
    def color_generator (no_colors):
        colors = []
        while len(colors) < no_colors:
            random_number = np.random.randint(0,16777215)
            hex_number = format(random_number, 'x')
            if len(hex_number) == 6: 
                hex_number = '#'+ hex_number
                colors.append (hex_number)
        return colors
    
    0 讨论(0)
  • 2020-11-29 02:15

    For generating random anything, take a look at the random module

    I would suggest you use the module to generate a random integer, take it's modulo 2**24, and treat the top 8 bits as R, that middle 8 bits as G and the bottom 8 as B.
    It can all be accomplished with div/mod or bitwise operations.

    0 讨论(0)
  • 2020-11-29 02:16

    Store it as a HTML color value:

    Updated: now accepts both integer (0-255) and float (0.0-1.0) arguments. These will be clamped to their allowed range.

    def htmlcolor(r, g, b):
        def _chkarg(a):
            if isinstance(a, int): # clamp to range 0--255
                if a < 0:
                    a = 0
                elif a > 255:
                    a = 255
            elif isinstance(a, float): # clamp to range 0.0--1.0 and convert to integer 0--255
                if a < 0.0:
                    a = 0
                elif a > 1.0:
                    a = 255
                else:
                    a = int(round(a*255))
            else:
                raise ValueError('Arguments must be integers or floats.')
            return a
        r = _chkarg(r)
        g = _chkarg(g)
        b = _chkarg(b)
        return '#{:02x}{:02x}{:02x}'.format(r,g,b)
    

    Result:

    In [14]: htmlcolor(250,0,0)
    Out[14]: '#fa0000'
    
    In [15]: htmlcolor(127,14,54)
    Out[15]: '#7f0e36'
    
    In [16]: htmlcolor(0.1, 1.0, 0.9)
    Out[16]: '#19ffe5'
    
    0 讨论(0)
提交回复
热议问题