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)

John Elder

John is the CEO of Codemy.com where he teaches over 100,000 students how to code! He founded one of the Internet's earliest advertising networks and sold it to a publicly company at the height of the first dot com boom. After that he developed the award-winning Submission-Spider search engine submission software that's been used by over 3 million individuals, businesses, and governments in over 42 countries. He's written several Amazon #1 best selling books on coding, and runs a popular Youtube coding channel.

View all posts

Add comment

Your email address will not be published. Required fields are marked *

John Elder