Overview:
- Kivy provides a switch widget which represents a setting in an App.
- The value represented by the switch is either True or False. That is the switch can be either in On position or Off position.
Retrieving the value of a Switch Widget:
- A switch widget can be associated with a callback to retrieve the value of the switch.
- The state transition of a switch is from either on to off or off to on.
- When the state transition is made on the switch the callback is triggered and the new state can be retrieved and any other action can be taken based on the state.
Example:
import kivy kivy.require('1.9.1')
from kivy.app import App from kivy.uix.switch import Switch from kivy.uix.gridlayout import GridLayout from kivy.uix.label import Label
# A Gridlayout with a label a switch class SwitchContainer(GridLayout): def __init__(self, **kwargs): super(SwitchContainer, self).__init__(**kwargs) self.cols = 2 self.add_widget(Label(text="Sample Settings:"))
self.settings_sample = Switch(active=False) self.add_widget(self.settings_sample)
self.settings_sample.bind(active=switch_callback)
# Callback for the switch state transition def switch_callback(switchObject, switchValue): print('Value of sample settings is:', switchValue)
# The App class SwitchExample(App): def build(self): return SwitchContainer()
# Run the kivy app if __name__ == '__main__': SwitchExample().run() |
Output:
Value of sample settings is: True Value of sample settings is: False |