Passing image object as a button background in Kivy

前端 未结 3 732
伪装坚强ぢ
伪装坚强ぢ 2021-02-08 01:52

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 w

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-08 02:24

    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("""
    :
        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()
    

提交回复
热议问题