Randomly Changing Color Button in Kivy

  • Share this:

Code introduction


This function creates a Kivy application that contains a button. Each time the button is pressed, the color of the button changes randomly.


Technology Stack : Kivy, randint, Image

Code Type : Kivy GUI Application

Code Difficulty : Intermediate


                
                    
def random_color_button():
    from kivy.app import App
    from kivy.uix.button import Button
    from kivy.uix.boxlayout import BoxLayout
    from random import randint
    from kivy.core.image import Image

    class RandomColorButtonApp(App):
        def build(self):
            layout = BoxLayout(orientation='vertical')
            self.button = Button(text='Press me', size_hint=(0.5, 0.2))
            self.button.bind(on_press=self.change_color)
            layout.add_widget(self.button)
            return layout

        def change_color(self, instance):
            r, g, b = randint(0, 255), randint(0, 255), randint(0, 255)
            self.button.background_color = (r / 255.0, g / 255.0, b / 255.0, 1)

    RandomColorButtonApp().run()