2

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
shamilpython
  • 479
  • 1
  • 5
  • 18
  • What is source for? Do you want it to be the background of the image? – eyllanesc Aug 14 '18 at 10:38
  • you could publish the .kv to make a translation to .py – eyllanesc Aug 14 '18 at 10:39
  • No, I wan't the sprite to _be_ the button itself. like think there is a 16x16 image of a cartoon tree. when I press it, it works just like a button and calls the function bind to it. And i would like a Python answer directly without KV -> PY translation – shamilpython Aug 14 '18 at 10:57
  • is that your code suggests that you have based on a .kv code because source is an attribute of Image and not of Button, I proposed to make the translation so that you understand the correspondences and can work with other codes since the view is created in the .kv – eyllanesc Aug 14 '18 at 11:03

1 Answers1

3

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()  
eyllanesc
  • 235,170
  • 19
  • 170
  • 241