Search code examples
kivycustom-widgetsevent-binding

Binding function to a button inside a Custom Widget from outside


I made this Widget:

<ImageButton>:
    source:''
    text:''
    release_fn: None
    Button:
        on_release: root.release_fn()
        size: root.size
        pos: root.pos
        BoxLayout:
            padding: 30
            size: self.parent.size
            pos: self.parent.pos
            orientation:'vertical'
            Image:
                id: img
                source: root.source
            Label:
                size_hint_y:.3
                text: root.text

Now I want to pass to it a function to be called when the button is released, but I can't figure out how to do it (and I couldn't find anything with the answer...)

The following gives me only a syntax error in the last line (the rest - and good working part - of the kivy file is omitted)

ImageButton:
    source: 'iconUsuario.png'
    text: 'Usuario'
    release_fn: print('HI!')


     print('HI!')
         ^
 SyntaxError: invalid syntax

Solution

  • Well, it turned out that it seemed not to be the best idea and I used a custom event:

    class ImageButton(Widget):
        def __init__(self,*args,**kwargs):
            super(ImageButton,self).__init__(*args,**kwargs)
            self.register_event_type('on_release')
    
        def on_release(self,*args):
            pass
    
        def callback(self,instance):
            self.dispatch('on_release')
            pass
    

    kv file:

    <ImageButton>:
        source:''
        text:''
        Button:
            on_release: root.callback(self)
            size: root.size
            pos: root.pos
            BoxLayout:
                padding: 30
                size: self.parent.size
                pos: self.parent.pos
                orientation:'vertical'
                Image:
                    id: img
                    source: root.source
                Label:
                    size_hint_y:.3
                    text: root.text