Reputation: 671
I am trying to make this simple script change a button's color when pressed with the on_press behavior.
Python Script: kivytest.py
#Import Libraries
#Import Kivy GUI
import kivy
#From kivy, import base class App
# app: always refers to instance of this application
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.stacklayout import StackLayout
################################################################################
# Creating the root widget used in the .kv file
class testLayout(StackLayout):
pass
################################################################################
class kivytestApp(App):
def build(self):
return testLayout()
test = kivytestApp()
test.run()
Corresponding .kv file: kivytest.kv
<StackLayout>:
#Create the canvas
canvas:
#Color the canvas background a dark gray with alpha = 1
Color:
rgba: 0.11, 0.15, 0.17, 1
Rectangle:
pos: self.pos
size: self.size
#Provide the orientation of the stack layout from left to right / top to bottom
orientation: "lr-tb"
#Add padding between children and layout
padding: 10
#Add spacing between each of its children
spacing: 5
Button:
size_hint: 0.2, None
text: "second button"
background_color: [1, 0, 0, 1]
background_normal: ''
on_press:
background_color: [0, 1, 0, 1]
print("second button pressed")
Unfortunately when I press the button in the app, the color remains red, but slightly darker red on_press, instead of green which I have specified. What should I correct? Is this implementation not as simple as it seems?
Upvotes: 2
Views: 261
Reputation: 244311
You have 2 errors:
By just indicating background_color you are creating a variable other than the background_color property of the Button. To refer to the same object that has the scope you must use self
.
You should not use :
in the assignment within an event but =
(I think it's a bug that kivy doesn't throw an error in this case)
Considering the above, the solution is:
on_press:
self.background_color = [0, 1, 0, 1]
print("second button pressed")
Upvotes: 3