mdoc-2011
mdoc-2011

Reputation: 2997

Fill GridLayout in Python's Kivy with an image

I have a kivy GridLayout of 3 rows, and nested BoxLayout in each row. I need to fill a box within a row entirely with an image. It maintains the image's original size regardless of adjustments I make within the kv file (e.g. size: self.size, size_hint_x: 1, and the steps outlined in this stack overflow Resizing an image to variable/fixed dimensions?).

Example screenshot for what I have - I'd like to enlarge the purple foo image to fill the entire red rectangle (aspect ratio isn't important to me): Screenshot

Some sample code:

<MyGridLayout>:

      rows: 3
      padding: 0
      spacing: 0

      BoxLayout:
          orientation: "horizontal"
          size_hint: 0.15, 0.2

          Button:
              text: 'FOO_BUTTON'
              size_hint_x: 0.25

          Label:
              text: ''


      BoxLayout:
          orientation: "horizontal"

          Image :
              source: 'C:/my/path.png'


          Label :
              size_hint_x: 0.3
              text: "foo"


      BoxLayout:
          orientation: "horizontal"
          Label :
              size_hint_x: 0.7
              text: "foo"

          Label :
              size_hint_x: 0.3
              text: "foo"

Upvotes: 2

Views: 1670

Answers (1)

FJSevilla
FJSevilla

Reputation: 4513

To make the image size maximized to fit in the image box you can use allow_stretch and keep_ratio properties:

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder

Builder.load_string("""
<MyGridLayout>:
    rows: 3
    padding: 0
    spacing: 0

    BoxLayout:
        orientation: "horizontal"
        size_hint: 0.15, 0.2

        Button:
            text: 'FOO_BUTTON'
            size_hint_x: 0.25

        Label:
            text: ''

    BoxLayout:
        orientation: "horizontal"

        Image :
            source: 'C:/my/path.png'
            allow_stretch: True
            keep_ratio: False

        Label :
            size_hint_x: 0.3
            text: "foo5"

    BoxLayout:
        orientation: "horizontal"
        Label :
            size_hint_x: 0.7
            text: "foo"

        Label :
            size_hint_x: 0.3
            text: "foo"
""")

class MyGridLayout(GridLayout):
    pass


class Test(App):
    def build(self):
        return MyGridLayout()


if __name__ == '__main__':
    Test().run()

Result:

enter image description here

Upvotes: 2

Related Questions