How to Create Checkbox in Kivymd-Python
Last Updated :
02 Jun, 2022
In this article, we will see how to add the Check box in our application using KivyMD in Python. KivyMD is a collection of Material Design compliant widgets which can be used with Kivy.
Installation:
To install these modules type the below command in the terminal.
pip install kivy
pip install kivymd
We will be discussing how to create square and circular check box in this article.
Square Check Box
Step 1: Import required packages.
For this, we will need Builder from kivy and MDApp from kivymd package.
Note: We will not be importing MDFloatLayout because we are designing our screen using kv language.
Python3
from kivy.lang import Builder
from kivymd.app import MDApp
|
Step 2: Design layout.
We will be designing our layout using kv language. First, we will declare the Layout widget class called MDFloatLayout and then the child widget class called MDCheckbox. We won’t pass any parameters to MDFloatLayout and keep it default. For MDSwitch we will pass its location in x,y coordinate form. center_x is used for the x coordinate whereas center_y is used for the y coordinate. And we also pass check box size using the size method and pass the values in dp. We will also be using size_hint to reduce effective area while tapping on the check box and passing None in parameters.
Step 3: Writing the main program.
To run kv file we will be using load_string() and pass our kv language in it. So we will define a function for this named build() and on-call it will load kv and return the screen. run() is used to run the class and it does not require any parameters.
Python3
class Test(MDApp):
def build( self ):
screen = Builder.load_string(KV)
return screen
Test().run()
|
Adding the above steps:
Python3
from kivy.lang import Builder
from kivymd.app import MDApp
KV =
class Test(MDApp):
def build( self ):
screen = Builder.load_string(KV)
return screen
Test().run()
|
Output:
Circular check box
For this example, we need to make some changes in our kv file to get a circular check box and the other procedure and functions will remain same as used in the above example. To make the check box circular we need to pass the group in our kv file.
Syntax:
MDFloatLayout:
MDCheckBox:
group:’group’
Implementation:
Python3
from kivy.lang import Builder
from kivymd.app import MDApp
KV =
class Test(MDApp):
def build( self ):
screen = Builder.load_string(KV)
return screen
Test().run()
|
Output:
Share your thoughts in the comments
Please Login to comment...