Random Color Rectangle with RGB Code Display

  • Share this:

Code introduction


This function uses the Bokeh library to generate a graphical interface that displays a rectangle filled with a random color, and also shows the RGB code of the color next to the rectangle.


Technology Stack : Bokeh, Python

Code Type : Graphical interface programming

Code Difficulty : Intermediate


                
                    
def random_color(arg1):
    import random
    from bokeh.plotting import figure, show
    from bokeh.models import ColumnDataSource
    
    # Generate a random color
    color = (random.random(), random.random(), random.random())
    
    # Create a simple figure with a rectangle
    p = figure(title="Random Color Rectangle", tools="")
    p.rect([0], [0], 1, 1, fill_color=color)
    
    # Create a ColumnDataSource to display the color
    source = ColumnDataSource(data=dict(color=[color]))
    
    # Add a text annotation to show the color code
    p.add_layout(bokeh.models.annotations.Text(x=0.5, y=0.5, text=f"Color: {color}", text_color="black"))
    
    # Display the figure
    show(p)                
              
Tags: