Reputation: 160
I'm using Kivy with Python 2.7. I am familiar with how to alter the color of the static button itself, but how do you change the color of the button when you press it? The default is blue.
Thanks for any help.
Upvotes: 0
Views: 4776
Reputation: 1
I'm sorry for that, I'm using a translator, it's just the first time I'm answering something on this site In general to avoid without unnecessary difficulties, you can make the following
button = Button(background_color=[1, 0,0,1]) # Creating a button
button.bind(on_press=lambda _: self.change_color(button,[0,0,0,1]))# If we get a button click event then we will call a lambda function that will call the function we need, this function will just change the color of our button while it is pressed
button.bind(on_release =lambda _: self.change_color(button,[1,0,0,1]))#The same thing will only work after the button has been released to return to the previous color
def change_color(btn, color):# Create a function that takes 2 required arguments: a button and the actual color we want to change to
btn.background_color=color#Changing the color of the button
I improved my answer because in the past on_touch_up worked all the time, regardless of whether the button was pressed or not, I didn't finish watching it:) This feature can be called for many different buttons, so it will save space probably.
Upvotes: 0
Reputation: 2403
The Kivy framework uses background images for button_normal and button_down, which the background_color only tints, so this in the kv language might not behave how you'd expect:
<Button>:
background_color: 1, 0, 0 # Tints the button red
background_normal: 'images/button_normal.png' # A clear image gives a bright red.
background_down: 'images/button_down.png' # A gray image gives a duller red.
border: (2, 2, 2, 2) # Don't stretch the outer two pixels on each edge when resizing.
This style lets you have say a dull border and bright inner and swap them round on the button press.If you use this system though, images will be imported with colours ignored. To fix this and solve your problem remove the background_color:
<Button>:
background_normal: 'images/button_normal.png' # Eg. A red button
background_down: 'images/button_down.png' # Eg. A green button
border: (2, 2, 2, 2) # Don't stretch the outer two pixels on each edge when resizing.
That'll change the colour of the buttons to whatever you've made in the image. It's worth noting that Kivy is excellent at stretching the images out, so if you have single colour buttons or tiny borders, you only need a tiny image, I use 8x8 pixels.
Upvotes: 1
Reputation: 5177
According to the reference for Button
, the property background_down
stores the path to an image used for the background while the Button
is pressed. This is the default:
background_down = StringProperty(
'atlas://data/images/defaulttheme/button_pressed')
You can change that property to point to a different image oratlas
.
Upvotes: 1