Introduction
We all have come across checkboxes on multiple websites. Checkboxes are specified two-state button that toggles between two states: checked or unchecked. This behavior is helpful in many scenarios making checkboxes one of the essential elements in any webpage.
Kivy is a platform-independent GUI tool in python that lets us run the code in Android, IOS, Linux, and Windows. Thus to create applications across different platforms, it would be great to use kivy. Therefore, combining the two most essential requirements, we come across how we can create a checkbox using the .kv file.
Thus, in this blog, we will learn how to create checkboxes in the .kv file.
Creating a Checkbox
With any other UI element, we also need to import the Checkbox from the module before we can start making a checkbox. First, we need to create the container class for the Checkbox.
import kivy
kivy.require("1.9.0")
# these are the imports we will need in the blog
from kivy.app import App
#imports the box layout
from kivy.uix.boxlayout import BoxLayout
#imports checkbox widget
from kivy.uix.checkbox import Checkbox
from kivy.core.window import Window
class testBox(BoxLayout):
#here we are defining the function that will be called when there is action in the checkbox
#the function here takes in the value i.e. the current status of the checkbox and prints the output accordingly. Here value is boolean
def checkbox_click(self, instance, value):
if value is True:
print("Checked")
else:
print("Unchecked")
class checkboxApp(App):
#here we are building the main component of our project
def build(self):
#we are defining the color of the window
Window.clearcolor=(0, 0, .30, .60)
return SampBoxLayout()
root = checkboxApp()
root.run()
Now we need to create the checkbox.kv file to make the Checkbox layout. The name of the .kv file should be the name of the function that we run in root i.e. checkboxApp here as any other name as the kv file will not include it in the run.
The below function is basically how we define the whole display of the GUI we are creating in a nested format where the nest basically defines one element as a parent and the other as a child element.
<testBox>:
#defines the orientation of the child elements
orientation: "vertical"
CustLabel:
#defines the content inside the label and the font size
text: "Profession"
font_size: 15
BoxLayout:
orientation: "horizontal"
height: 15
CustLabel:
text: "Student"
font_size: 12
CheckBox:
#defines which function to call when there is some action in the checkbox and passes the status of the checkbox as an argument
on_active: root.checkbox_click(self, self.active)
CustLabel:
text: "Other"
font_size: 12
CheckBox:
on_active: root.checkbox_click(self, self.active)
Now we can create a checkbox using the .kv file.