【问题标题】:Fill GridLayout in Python's Kivy with an image用图像填充 Python 的 Kivy 中的 GridLayout
【发布时间】:2018-05-18 15:43:27
【问题描述】:

我有一个 3 行的 kivy GridLayout,每行都嵌套了 BoxLayout。我需要用图像完全填充一行中的一个框。无论我在 kv 文件中进行何种调整(例如size: self.size、size_hint_x: 1 以及此堆栈溢出中概述的步骤Resizing an image to variable/fixed dimensions?),它都会保持图像的原始大小。

我所拥有的示例屏幕截图 - 我想放大紫色 foo 图像以填充整个红色矩形(纵横比对我来说并不重要):

一些示例代码:

<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"

【问题讨论】:

    标签: python image kivy


    【解决方案1】:

    要使图像大小最大化以适合图像框,您可以使用allow_stretch 和keep_ratio 属性:

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

    结果:

    【讨论】:

      猜你喜欢
      • 2014-07-16
      • 2016-04-29
      • 2022-01-05
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-21
      相关资源
      最近更新 更多