Introduction
We know how important a button is, however in some cases we find it better to describe a button using an image rather than simple text. Here, we are able to do this with the help of buttons in kivy as well. In this blog, we will learn about how we can bring into reality what we discussed earlier using the button module from kivy.uix module.
Creating an Image Button
The basic approach here would be to import the kivy and the kivy app and then create a class to extend and create a button with a background as an image. For the image, we will store two images back1.png and back2.png. We have 2 images to have two images when the image is clicked and released respectively.
Before we start coding we need to learn about the three properties of the button that define the background of any button created using kivy:
- background_down: Used to specify the default background image when the button is pressed and has one parameter of string type passed into it.
- background_normal: Used for the default background when the button is not pressed and also contains a string parameter.
- background_disabled_normal: When the button is disabled and not pressed this property specifies the graphical background of the button.
Also Read - Image Sampling
Now we code the example:
Example
import kivy
from kivy.app import App
from kivy.uix.button import Button
kivy.require('1.9.0')
#our class to create a button and execute it
class ButtonApp(App):
def build(self):
# create an image a button
# Adding images back1.png image as button
# Adding image back2.png as the background when clicked
testBtn = Button(text ="Hello World !",
background_normal = 'back1.png',
background_down ='back2.png'
)
return testBtn
# binding ButtonApp to a root
root = ButtonApp()
root.run()
Now that we have successfully created an image button, we need to add some functionality to it now. For that, we use the bind() function and bind a callback to the on-click event.
def build(self):
# create a fully styled functional button
testBtn = Button(text ="Hello World !",
background_normal = 'back1.png',
background_down = 'back2.png'
)
# bind() use to bind the button to function callback
testBtn.bind(on_press = self.callback)
return testBtn
# callback function tells when button pressed
def callback(self, event):
print("Hello World Again")