Random Color Generator for Kivy

  • Share this:

Code introduction


This function generates a random color value and converts it to the color format used in Kivy. The function first imports the necessary modules, defines a ColorPicker class to display the color, and then defines a get_random_color function to generate a random color.


Technology Stack : Kivy, random, Image, Widget, Color, Rectangle

Code Type : Kivy UI

Code Difficulty : Intermediate


                
                    
def random_color():
    import random
    from kivy.uix.widget import Widget
    from kivy.core.image import Image
    from kivy.graphics import Color, Rectangle

    class ColorPicker(Widget):
        def __init__(self, **kwargs):
            super(ColorPicker, self).__init__(**kwargs)
            self.size = (100, 100)
            self.color = (1, 0, 0, 1)  # 默认红色
            self.draw_color()

        def draw_color(self):
            with self.canvas:
                Colorrgba = self.color
                Color(*Colorrgba[:3])
                Rectangle(size=self.size)

    def get_random_color():
        color = (random.random(), random.random(), random.random(), 1)
        return color

    return get_random_color()