Kivy App with Random Widget Color Generation

  • Share this:

Code introduction


The code uses the Kivy package, specifically the RandomWidget class, which inherits from Widget. The RandomWidget class generates random colors for its widgets. The application is built using the App class from the Kivy.app module.


Technology Stack : The code utilizes the Kivy library, specifically the RandomWidget class, which extends the Widget class. Random colors are generated for each widget within the class. The application is constructed using the App class from the Kivy.app module.

Code Type : The type of code

Code Difficulty : Advanced


                
                    
from kivy.uix.widget import Widget
from random import randint
from kivy.core.window import Window
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

class RandomWidget(Widget):
    def __init__(self, **kwargs):
        super(RandomWidget, self).__init__(**kwargs)
        self.size_hint = (None, None)
        self.width, self.height = Window.size[0] * 0.2, Window.size[1] * 0.2
        self.color = (randint(0, 255) / 255.0, randint(0, 255) / 255.0, randint(0, 255) / 255.0, 1)

def random_widget_app():
    class RandomWidgetApp(App):
        def build(self):
            layout = BoxLayout(orientation='vertical')
            for _ in range(5):
                widget = RandomWidget()
                layout.add_widget(widget)
            return layout

    RandomWidgetApp().run()