In this video I’ll show you how to change the color of buttons with Kivy.

Kivy uses a kind of weird color system that looks like this (1,1,1,1) where each of those 1’s represents a color (Red, Green, Blue, and Alpha).

To choose colors, divide the RGB value you want by 255.0 to get the kivy color code.

I’ll also show you a hacky way to use hex color codes instead of the weir (1,1,1,1) thing.

Python Code: color.py

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.lang import Builder


# Designate Our .kv design file 
Builder.load_file('color.kv')


class MyGridLayout(Widget):
	
	name = ObjectProperty(None)
	pizza = ObjectProperty(None)
	color = ObjectProperty(None)


	def press(self):
		name = self.name.text
		pizza = self.pizza.text
		color = self.color.text

		#print(f'Hello {name}, you like {pizza} pizza, and your favorite color is {color}!')
		# Print it to the screen
		#self.add_widget(Label(text=f'Hello {name}, you like {pizza} pizza, and your favorite color is {color}!'))
		print(f'Hello {name}, you like {pizza} pizza, and your favorite color is {color}!')
		# Clear the input boxes
		self.name.text = ""
		self.pizza.text = ""
		self.color.text = ""

class AwesomeApp(App):
	def build(self):
		return MyGridLayout()


if __name__ == '__main__':
	AwesomeApp().run()




Kivy Design Code: color.kv

#:import utils kivy.utils
<MyGridLayout>
	
	name:name
	pizza:pizza
	color:color

	GridLayout:
		cols:1
		size: root.width, root.height
		GridLayout:
			cols:2

			Label:
				text: "Name"
				background_color: utils.get_color_from_hex('#fa00df')
			TextInput:
				id: name
				multiline:False
				background_color: utils.get_color_from_hex('#fa00df')

			Label:
				text: "Favorite Pizza"
			TextInput:
				id: pizza
				multiline:False
				
			Label:
				text: "Favorite Color"
			TextInput:
				id: color
				multiline:False	
				
		Button:
			text: "Submit"
			font_size: 32
			on_press: root.press()
			#RGB - A
			background_normal: ''
			#background_color: (238/255.0,250/250.0,0/250.0,1)

			background_color: utils.get_color_from_hex('#fa00df')


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