Search code examples
pythonbuttonkivykivy-language

How to make custom buttons in Kivy with the KV Language?


I am trying to use a custom sprite to make a custom button. I know how I can do this in the KV Language, but I'd rather stick with Python.

I saw that setting some source attribute to the sprite worked in the KV Language, so I tried this:

from kivy.app import App
from kivy.uix.button import Button

class RoundButton(Button):
    def __init__(self, **kwargs):
        Button.__init__(self, **kwargs)
        self.source = '/home/shamildacoder/Pictures/Painting.png'

class TestApp(App):
    def build(self):
        return RoundButton(text='HELLO WORLD')

TestApp().run()

But this just shows a normal button. Any help?


Solution

  • From what I understand you want an Image where you are allowed to handle the on_press event, for it the Behaviors as I show below:

    from kivy.app import App  
    from kivy.uix.behaviors import ButtonBehavior  
    from kivy.uix.image import Image  
    
    
    class ImageButton(ButtonBehavior, Image):
        pass
    
    class MyApp(App):  
        def build(self):  
            return ImageButton(source="kivy.png", on_press=lambda *args: print("press"))
    
    if __name__ == "__main__":  
        MyApp().run()