How to use kv language In Python

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 and MDSwitch because we are designing our screen using kv language. 

Python3




# import packages
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 MDSwitch. We won’t pass any parameters to MDFloatLayout and keep it default. 

For MDSwitch we will pass it’s location in x,y coordinate form. center_x is used for the x coordinate whereas center_y is used for the y coordinate.

Python3




# writing kv lang
KV = '''
 
# declaring layout
MDFloatLayout:
     
    # this will create a switch
    MDSwitch:
        # giving position to the switch on screen
        pos_hint: {'center_x': .5, 'center_y': .5}
'''


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




# app class
class Test(MDApp):
    def build(self):
       
        # this will load kv lang
        screen = Builder.load_string(KV)
         
        # returning screen
        return screen
 
# running app
Test().run()


Adding the above Steps:

Python3




# importing packages
from kivy.lang import Builder
from kivymd.app import MDApp
 
# writing kv lang
KV = '''
 
# declaring layout
MDFloatLayout:
     
    # this will create a switch
    MDSwitch:
        # giving position to the switch on screen
        pos_hint: {'center_x': .5, 'center_y': .5}
'''
 
# app class
class Test(MDApp):
    def build(self):
       
        # this will load kv lang
        screen = Builder.load_string(KV)
         
        # returning screen
        return screen
 
# running app
Test().run()


Output:

Create switch with Python-kivymd

In this article, we will see how to add the switch in our application using KivyMD in Python.

MDSwitch: The switch is a kind of toggle button mostly used in android apps to on/off features.Its looks as:

 

Similar Reads

Installation:

To install the modules type the below command in the terminal....

Method 1: Using kv language:

Step 1. Import required packages....

Method 2. Without kv language:

...