Combining image and text within a button in kivy

后端 未结 3 1908
庸人自扰
庸人自扰 2021-02-04 10:05

What\'s the preferred way to combine an image/icon and text within a button? For example, how would you create a button with text = \'my button\', and a graphical i

3条回答
  •  半阙折子戏
    2021-02-04 10:33

    Regarding to question #2.

    The way Kivy works is embedding Widget instances. Since Image and Button are subclasses of Widget, then all you have to do is embed an Image inside a the Button. Notice that the positioning inside a widget is fixed. You have to give explicit coordinates.

    That said, you can always embed a Layout to organize the stuff you are putting inside the Button.

    Here is the simple ex

    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 - 200
                x: self.parent.x
        Label:
            text: "A label"
    """)
    
    class ButtonsApp(App, BoxLayout):
        def build(self):
            return self
    
    if __name__ == "__main__":
        ButtonsApp().run()
    

    EDIT: An example of how a relative layout can be embedded inside a button

    In this case I am using a StackLayout to organize an Image and a Label inside. As I said, Button is a Widget and Kivy works embedding widgets inside widgets. It doesn't matter if they are labels, buttons or layouts.

    from kivy.app import App
    from kivy.uix.boxlayout import BoxLayout
    from kivy.lang import Builder
    
    Builder.load_string("""
    :
        orientation: "vertical"
        Button:
            StackLayout:
                pos: self.parent.pos
                size: self.parent.size
                orientation: 'lr-tb'
                Image:
                    source: 'kivy.png'
                    size_hint_x: None
                    width: 74
                Label:
                    size_hint_x: None
                    width: 100
                    text: "The text"
        Label:
            text: "A label"
    """)
    
    class ButtonsApp(App, BoxLayout):
        def build(self):
            return self
    
    if __name__ == "__main__":
        ButtonsApp().run()
    

提交回复
热议问题