python - 在Python的Kivy中用图像填充GridLayout

标签 python image kivy

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

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

一些示例代码:

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

最佳答案

要使图像尺寸最大化以适合图像框,您可以使用 allow_stretchkeep_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()

结果:

enter image description here

关于python - 在Python的Kivy中用图像填充GridLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47645843/

相关文章:

python - 如何在 Python IDLE Shell 中获取终端高度(以行为单位)?

python - 如何删除或替换 zip 存档中的文件?

python - 计算字符串中某个子串的重复出现次数

java - 在 Android 中 move 图像

image - LoadMask 图像 - extjs

python - 从多个文件中提取一列并将其粘贴到一个文件中

ios - 设置UIButton共享快速操作图标

python - 如何在Android中保持kivy服务在后台运行(切换到其他应用程序或锁定屏幕时服务仍然运行)?

android - 无法在 kivy launcher for android 中运行 "hello world"python 代码

python - Kivy BoxLayout 将小部件与顶部边框对齐