Method Without kv language
Step 1. Import required packages.
For this, we will need Screen, MDSwitch, and MDApp from kivymd package.
Python3
# import packages from kivymd.app import MDApp from kivymd.uix.screen import Screen from kivymd.uix.selectioncontrol import MDSwitch |
Step 2. Writing the main program.
To design a layout first we will need a black layout, for which we will use screen(). Now we need to define MDSwitch. We can do that using MDSwitch(), In this method, we used the same parameter used in method 1 which will be used to define their location on-screen using x,y coordinates. After all this, we have to MDSwitch widget to the screen and to do so we will be using add.widget(), where parameters will be the widget that we want to add to the screen. And that’s all now we will run the app class using run().
Python3
# App class class MainApp(MDApp): def build( self ): # defining blank screen/layout. screen = Screen() # defining MDSwitch widget and storing in a variable wid = MDSwitch(pos_hint = { 'center_x' : 0.5 , 'center_y' : 0.5 }) # adding widget to the screen screen.add_widget(wid) # returns screen/layout return screen # running app MainApp().run() |
Adding the above Steps:
Python3
# import packages from kivymd.app import MDApp from kivymd.uix.screen import Screen from kivymd.uix.selectioncontrol import MDSwitch # App class class MainApp(MDApp): def build( self ): # defining blank screen/layout. screen = Screen() # defining MDSwitch widget and storing in a variable wid = MDSwitch(pos_hint = { 'center_x' : 0.5 , 'center_y' : 0.5 }) # adding widget to the screen screen.add_widget(wid) # returns screen/layout return screen # running app MainApp().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:
Contact Us