Ingap.dev - A Personal Dev Blog

If the only tool you have is a hammer, it is tempting to treat everything as if it were a nail. (Abraham Maslow)

Published on Tuesday 3 November 2020

Tags: functools1 GUI2 kivy3 oop2

[Python] Kivy: Bind button to a class method with arguments

Here's how to bind an object's event to a class method in Kivy, a Python framework for creating cross-platform applications.


Since Kivy beginners can have unexpected errors after binding an object's event to a class method, I'm very briefly explaining how to do it correctly with an example. If you need a background on how can a layout be defined, read this.

Our sample class method printing the first two arguments:

def myClassMethod(self,firstArg,secondArg):
    print(firstArg)
    print(secondArg)

Button defined in the Python code:

from functools import partial 
#...
def createButtons(self):
    #...
    self.btn = Button(text="ButtonText")
    self.btn.bind(on_press=partial(self.myClassMethod, 1000))

Note: the partial function plays a similar role as lambda and is used to avoid the automatic execution of the class method. To know more about the partial function, read this. It's enough to know that we are passing to myClassMethod just one input parameter, which is the integer 1000.

When the button is pressed, the terminal shows something like:

1000
<kivy.uix.button.Button object at 0x0000020876C79748>

In other words, firstArg is our input parameter (i.e. 1000) while secondArg automatically corresponds to the object which triggered the method's call. Indeed, we can use it to show button properties like e.g. its text with:

def myClassMethod(self,firstArg,secondArg):
    print(firstArg)
    print(secondArg.text)

Output:

1000
ButtonText