Search code examples
pythonpython-3.xkivykivy-language

Can't bind a function to a button


I can't seem to bind my function to this certain button. I have tried this:

This is my function:

def callback(str):
    print('he button <%s> is being pressed' % str)

and this is where i bind the function:

btn = Button(text="%s" % feedList[i]['message'])
btn.bind(on_press=callback(i))

Solution

  • You should pass function name when binding:

    btn.bind(on_press=callback)
    
    # ...
    
    def callback(instance, value):
        print('My button <%s> state is <%s>' % (instance, value))
    

    If you want to pass i to callback also you can use partial function:

    from functools import partial
    
    btn.bind(on_press=partial(callback, i))
    
    # ...
    
    def callback(i, instance, value):
        print('My button <%s> state is <%s>' % (instance, value))