Combining image and text within a button in kivy

后端 未结 3 1847
庸人自扰
庸人自扰 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:10

    Define a new Button class or modify the one in Kivy.uix.button

    class MyButton(Button):
        #add these three properties in the class
        icon = ObjectProperty(None)
        icon_size = (0,0)
        icon_padding = NumericProperty(0)    #Enter any default value like 50 if you will
                                             #always use an icon, or specify this field
                                             #while creating the button
        def __init__(self, **kwargs):
            #no changes here, just for reference
            return super(MyButton, self).__init__(**kwargs)
    

    KV file:

    :
    state_image: self.background_normal if self.state == 'normal' else self.background_down
    disabled_image: self.background_disabled_normal if self.state == 'normal' else self.background_disabled_down
    canvas:
        Color:
            rgba: self.background_color
        BorderImage:
            border: self.border
            pos: self.pos
            size: self.size
            source: self.disabled_image if self.disabled else self.state_image
    
        Color:
            rgba: (1, 1, 1, 1) if root.icon != None else (1,1,1,0)
    
        Rectangle:
            source: root.icon
            size: (self.texture_size[1],self.texture_size[1]) if self.icon_size == (0,0) else self.icon_size
            pos: int(self.center_x - self.texture_size[0] / 2.)-dp(root.icon_padding), int(self.center_y - self.texture_size[1] / 2.)
    
        Color:
            rgba: 1, 1, 1, 1
    
        Rectangle:
            texture: self.texture
            size: self.texture_size
            pos: int(self.center_x - self.texture_size[0] / 2.)+dp(root.icon_padding), int(self.center_y - self.texture_size[1] / 2.)
    

    Now just create a button widget

    MyButton(text = 'Hello',icon = 'icon.png', icon_padding = 50)
    

提交回复
热议问题