In this Python Kivy article we want to learn that How to Create Switch in Python Kivy, Kivy is powerful Python framework for building cross platform user interfaces, including mobile and desktop applications. in this article we want to talk that how to create a switch in Kivy, switch is a widget that allows users to toggle between two states.
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.switch import Switch class MyWidget(Widget): def __init__(self, **kwargs): super(MyWidget, self).__init__(**kwargs) self.switch = Switch(pos=(100, 100)) self.switch.bind(active=self.on_switch_active) self.add_widget(self.switch) def on_switch_active(self, switch, active): if active: print("Switch is on") else: print("Switch is off") class SwitchApp(App): def build(self): return MyWidget() if __name__ == '__main__': SwitchApp().run() |
In the above code first we have imported kivy.
1 2 3 |
from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.switch import Switch |
Next step is to create a switch using the Switch class. the constructor takes no arguments, in here we are creating a switch and adding it to a widget using add_widget method.
1 2 3 4 5 |
class MyWidget(Widget): def __init__(self, **kwargs): super(MyWidget, self).__init__(**kwargs) self.switch = Switch(pos=(100, 100)) self.add_widget(self.switch) |
The final step is to add functionality to the switch. we can do this by binding a function to the switch on_active event, in here we are creating a function called on_switch_active that takes two arguments, the switch that triggered the event and its new active state. inside the function we check whether the switch is on or off and print a message.
1 2 3 4 5 6 7 8 9 10 11 12 |
class MyWidget(Widget): def __init__(self, **kwargs): super(MyWidget, self).__init__(**kwargs) self.switch = Switch(pos=(100, 100)) self.switch.bind(active=self.on_switch_active) self.add_widget(self.switch) def on_switch_active(self, switch, active): if active: print("Switch is on") else: print("Switch is off") |
Run the complete code and this will be the result
