Random Color Changing Button with Kivy

  • Share this:

Code introduction


This code creates a Kivy-based Python application that includes a button. When the button is pressed, the button's background color changes randomly, and a label below indicates that the color has changed.


Technology Stack : Kivy, Python, App, Button, Layout, Color Change, Random Selection

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_color_button(text="Click me", size=(100, 50)):
    from kivy.app import App
    from kivy.uix.boxlayout import BoxLayout
    from kivy.uix.button import Button
    from kivy.uix.label import Label
    import random

    class RandomColorButtonApp(App):
        def build(self):
            layout = BoxLayout(orientation='vertical', spacing=10)
            self.button = Button(text=text, size=size)
            self.button.bind(on_press=self.change_color)
            layout.add_widget(self.button)
            self.label = Label(text="Press the button to change color")
            layout.add_widget(self.label)
            return layout

        def change_color(self, instance):
            colors = ["#FF5733", "#33FF57", "#3357FF", "#FF33C7", "#C7FF33"]
            color = random.choice(colors)
            self.button.background_color = [int(color[i:i+2], 16)/255.0 for i in range(0,6,2)]
            self.label.text = "Color changed!"

    return RandomColorButtonApp().run()