Switch widget in Kivy | Python
In this tutorial, you are going to learn about the Switch widget in Kivy of Python.
First of all, we have to learn about the widget in Kivy.
What is a widget in Kivy?
A widget is the foundation of the block of GUI interfaces that is used in Kivy. It prepares a canvas that can be used to draw on the screen. It receives inputs and outputs from them. Here events mean input given by the user and the output becomes a reaction.
The widgets are arranged by trees and it has a root widget. It is manipulated by the following methods: add_widget(), remove_widget(), clear_widget().
What is the Switch widget in Kivy?
The Switch widget is operative or inoperative, as a mechanical switch. The user can swipe switch to the left/right to On/Off or activate/deactivate it.
from kivy.app import App from kivy.uix.switch import Switch from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label class SwitchWidget(BoxLayout): def __init__(self, **kwargs): super(SwitchWidget, self).__init__(**kwargs) self.cols = 2 self.add_widget(Label(text ="Switch widget")) self.settings_sample = Switch(active = False) self.add_widget(self.settings_sample) class SwitchApp(App): def build(self): return SwitchWidget() if __name__ == '__main__': SwitchApp().run()
Output1: Switch Widget1
Output2: Switch Widget2
First of all, import App from Kivy app
From kivy import Switch.
From kivy import box layout.
From kivy import Label.
Create a class that contains all details about Switch Widget.
Defining a constructor that is initialized.
Use the super function to access the inherit methods which are connected to parent class.
Assign the columns which you want.
Add label to the switch and firstly the switch is off position.
Next, add the widget to the switch.
Create the class for App and define the build function and return the function.
To run the kivy app call the function by using if condition.
This is about how to create a Switch Widget in Kivy Python.