Learning Kivy with Example: Part III

Learning Kivy with Example: Part II**

This is the last part of the project. In this part, we will activate the functionality in the main app, so that it works the way it should.

This far, our skeleton is complete, The GUI is ready. Now we work on the functionality.

Let's Begin . . .

In our main.py file inside the container class we have 3 functions, add_one, subtract_one and multiply. let's start with the add_one function. We will add 1 to the existing value with this function. But where is the 'value' that we are talking about !? Remember we created a Label in the main.kv file with a text field? That is the 'value' we are talking about. This was the default output. We need to bring that data into this function and do some arithmetic operation on that. How will we bring the data into the function then?

To do that we need to use the ObjectProperties module from kivy.properties. This module provides us the ability to aggregate the attributes of any given object, in our case the Container from the "main.kv" file. To make Container accessible via ObjectProperty we need to add a custom attribute in the Container. in the main.kv we add this line.

<Container>:
    dp: display
    rows:2
    ...
    ...

now in the main.py file we can import the ObjectProperties module and inside the container call it in.

from kivy.properties import ObjectProperty
...
...

class Container(GridLayout):
    dp = ObjectProperty()

Now we can start working on the functions and activate them. starting with the add_one function. Our goal here is to grab the value from the Label and add 1 to it and return it as the replacement string of output. We have already grabbed the Label via the ObjectProperty. If you haven't noticed, we added the custom attribute to the container class, which binds dp to display, display is the id of Label. so by calling dp.text, we can get Label.text. Let's do it.

def add_one(self):
    value = int(self.dp.text)
    self.dp.text = str(value + 1)

At first, we grab the text value and parse it into Int. then we increment the value by one, parse it as a string and replace the existing value of Label.text by saving the string value in dp.text. for the rest of the functions, the process is the same just variation the arithmetics, as you can see right here

def subtract_one(self):
    value = int(self.dp.text)
    self.dp.text = str(value - 1)

def multiply(self):
    value = (int(self.dp.text) - 1) * (int(self.dp.text) + 1)
    self.dp.text = str(value)

And We are Done!.... This App is complete now with all its intended functionalities.

Run the main.py file to see your application working.

Find the Source Code Here

Quick Access

Faster way to traverse the blog