Changing background of a Button to a different shape and Styles like shadow effect etc in kivy python
Button in kivy starts with a ButtonBehavior which is combined with a Label adding properties like background_normal/down...for handling textures on the canvas.
Knowing this you can simply combine ButtonBehavior with any other widget you choose. Eg.
from kivy.base import runTouchApp
from kivy.lang import Builder
kv = '''
<ButImage@ButtonBehavior+AsyncImage>
FloatLayout:
# we don't specify anything here so float layout takes the entire size of the window.
ButImage:
id: but
# take 50% size of the FloatLayout
size_hint: .5, .5
# Make Button change it's opacity when pressed for visual indication
opacity: 1 if self.state == 'normal' else .5
source: 'http://www.victoriamorrow.com/sitebuildercontent/sitebuilderpictures/enter_button.gif'
# Introduce Label incase you want text on top of the image
Label:
center: but.center
# change text acc to but state
text: "Normal" if but.state == 'normal' else 'down'
'''
if __name__ == '__main__':
runTouchApp(Builder.load_string(kv))
Here we just set the ButtonBehavior to be combined with a AsyncImage which downloads the image from web for your background.
you should see something like this
Animation affect in background
This would be as simple as changing the source to animated gif or list of images inside a .zip.
from kivy.base import runTouchApp
from kivy.lang import Builder
kv = '''
<ButImage@ButtonBehavior+AsyncImage>
FloatLayout:
ButImage:
id: but
size_hint: .5, .5
opacity: 1 if self.state == 'normal' else .5
allow_stretch: True
keep_ratio: False
source: 'http://media1.policymic.com/site/article-items/2095/1_gif.gif'
Label:
center: but.center
text: "Normal" if but.state == 'normal' else 'down'
'''
if __name__ == '__main__':
runTouchApp(Builder.load_string(kv))
Look at the sequence images example This was done before ButtonBehaviors were introduced so it even has a example of a AnimatedButton class using the older method which is essentially not needed any more.
Shadow Effect:
There are many ways to do this too.
You could either add a shadow to a widget/layout and have the button on top of this widget/layout take up less space than the shadow so as to account for touch on the shadows.
Or Create your own CustomButtonBehavior class derived from ButtonBehavior that overrides collidepoint
method to only return True for custom collision. There is a example of using custom collision for widgets. You could even set the Image's keep_data
property to True and later check pixel data for alpha to determine if you want to return true for collision.
Rounded edges etc.
Simply use a image with rounded edges kivy supports use of BorderImage Instruction which is equivalent to css borderimage in terms of functionality. Kivy's own button by default uses this. Try and experiment with border attribute of BorderImage.