Random Color Generation with Textual Library

  • Share this:

Code introduction


This function uses the Color class from the Textual library to generate a random color. It provides two methods to generate colors: one is to generate a hexadecimal color code, and the other is to generate an RGB color object. The function returns one of these two methods.


Technology Stack : Textual library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_color_generator():
    import random
    from textual.colors import Color
    
    def random_hex_color():
        return f'#{random.randint(0, 0xFFFFFF):06X}'
    
    def random_rgb_color():
        return Color(
            r=random.randint(0, 255),
            g=random.randint(0, 255),
            b=random.randint(0, 255)
        )
    
    return random.choice([random_hex_color, random_rgb_color])()