In this video I’ll show you how to easily add a switch to your Kivy App.
Switches are great for toggling things on or off. To create a switch, just define it in your .kv file and set an on_active function that we can define on the python backend.
The switch will pass a switchValue when clicked that is either True or False. Then we can run a simple if statement to determine whether the switch has been switched to on or off, and take action accordingly.
Python Code: switch.py
GitHub Code: switch.py
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
# Designate Our .kv design file
Builder.load_file('switch.kv')
class MyLayout(Widget):
def switch_click(self, switchObject, switchValue):
if (switchValue):
self.ids.my_label.text = "You clicked the Switch On!!"
else:
self.ids.my_label.text = "You clicked the Switch Off!!"
#self.ids.my_switch.disabled = True
class AwesomeApp(App):
def build(self):
return MyLayout()
if __name__ == '__main__':
AwesomeApp().run()
Kivy Design Code: switch.kv
GitHub Code: switch.kv
<MyLayout> BoxLayout: orientation: "vertical" size: root.width, root.height Label: id: my_label font_size: 32 text: "The Switch Is On!" Switch: id: my_switch active: True disabled: False font_size: 32 on_active: root.switch_click(self, self.active)

Add comment