13

In Kivy, is there a way to pass image object as a button background, instead of image file name?

button.background_normal property accepts only strings. I would like to customize image properties, such as allow_stretch = False.

If that succeeds, how can I specify image alignment inside a button, eg. to make it top-left aligned?

blablatros
  • 733
  • 1
  • 7
  • 21

3 Answers3

17

The source is just a property of Button and it is a string as you pointed out. You want a Widget inside a Widget, and that is the basic way Kivy works. So just add the Image as it is. A little bit of positioning would do the rest.

You have to be careful with the positioning. Make sure it is in a visible part and nothing covers it. I use a Label after the button because it has transparent Color so you can experimenting with it. For example if your positioning is wrong (try x:0 y:0) you can see the button going to the bottom-left corner in the label area.

The image I am using is the Kivy logo:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string("""
<ButtonsApp>:
    orientation: "vertical"
    Button:
        text: "B1"
        Image:
            source: 'kivy.png'
            y: self.parent.y + self.parent.height - 250
            x: self.parent.x
            size: 250, 250
            allow_stretch: True
    Label:
        text: "A label"
""")

class ButtonsApp(App, BoxLayout):
    def build(self):
        return self

if __name__ == "__main__":
    ButtonsApp().run()
toto_tico
  • 17,977
  • 9
  • 97
  • 116
  • Thank you, it works great. I somehow thought that widgets could be added only to layout widgets; I was not aware that they could be added on top of any other widget. – blablatros Jul 01 '13 at 21:54
  • I think this example should be included right at http://kivy.org/docs/api-kivy.uix.button.html because now it looks like the only way to set background image is `background_normal`. – martin May 20 '15 at 15:45
  • Why does `pos_hint: {"center_x": 0.5, "center_y": 0,5}` under `Ìmage` not work? – Nearoo Sep 12 '16 at 17:00
  • ...because `pos_hint` only work inside layouts. You will have to add an intermediate layer (try `FloatLayout`) between Button and Image in order to activate `pos_hint` and `size_hint` properties. No worries about adding widgets inside widgets; they are very cheap in Kivy and this is actually the proper way of working with it. – toto_tico Sep 13 '16 at 22:57
  • Is there a way to do this without the .kv markup, that is, in pure (Kivy) Python? – Joshua Harwood Aug 13 '20 at 00:43
14

In addition to toto_tico's answer, you can locate the image at the center of the button as:

Button:
    id: myButton
    Image:
        source: "./buttonImage.PNG"
        center_x: self.parent.center_x
        center_y: self.parent.center_y
Guray Yildirim
  • 321
  • 3
  • 7
1

You can use

Button:

  id:mybutton

  background_down: "bgdown.png"

  background_normal: "bg.png"