How is build() function called in Kivy, Python, Even though we never call it by ourselves!

Hi,

When you start to learn Kivy, everything appears to be somewhat different from Tkinter. If we are not familiar with the “Overriding Methods” in Object Oriented Programming, then this doubt comes to mind. How does build() function get called in App class.

Look at the following code.

class MyApp(App):
    def build(self):
        return Label(text="This is My App"

if __name__ == "__main()__":
    MyApp().run()

When we run this code, the output would show us a window with a text “This is My App”. When we look only at the above code, we see that this text was created using the build() method inside the MyApp class. But we used a run() method, not build() method, so how did the build() method come into action by itself. We never called it by ourselves, correct? Yes! That is correct, we never called the method by ourselves, but the Kivy module called it for us.

There is a run() method inside the App module in Kivy. Let’s take a look at how this method is defined inside the App module of Kivy. You can find the following code by searching for Kivy folder in your hard disk and look for the file App.py inside it. Open this file and look for this function given at almost the end of the file.

def run(self):
'''Launches the app in standalone mode.
'''
self._run_prepare()
runTouchApp()
self.stop()

We can see that the run() method calls another method run_prepare(), and when we look into this method’s definition, we can see that our build() method is being called.

def _run_prepare(self):
if not self.built:
self.load_config()
self.load_kv(filename=self.kv_file)
root = self.build()
if root:
self.root = root

A variable named ‘root’ is created once this method is called. Now, what if we don’t define the build() method by ourselves within that App class?

Even in that case, we get a blank window, and yes the build() function is already defined within Kivy. Let’s have a look at the build() function that is already defined within this App.py file.

def build(self):

if not self.root:
return Widget()

It returns a Widget object. Hence, we can see that even though we didn’t call for this function, this function automatically gets called and a Widget class object named ‘root’ gets formed.

When we define the build() function by ourselves, we simply over-ride the already defined function within the App class, which is the parent class to your MyApp.

Thanks!

Leave a Comment

Your email address will not be published. Required fields are marked *

PHP Code Snippets Powered By : XYZScripts.com