如何使用按钮将图像加载到 kivy window 中?

How do I load an image into a kivy window using a button?

我正在尝试使用带有 Python 的 kivy 来开发一个带有滑块的快速应用程序,其中必须首先使用滑块来确定设置,然后单击 'Submit' 然后加载所需的图片导入应用 window.

目前我的 .kv 文件中有单独插入按钮和图像的示例,但我不确定如何连接它们:

BoxLayout:
    orientation:'vertical'
    size: root.width,root.height
    font_size: 20
    padding: 100
    spacing: 10

    Button:
        text: 'press me'
        on_press: print("ouch! More gently please")
        on_release: print("ahhh")
        on_state:
        #print("my current state is {}".format(self.state))
        size_hint: (0.3,0.3)

    Image:
        source: 'images\IMG_6980.jpg'
        #allow_stretch: True
        #keep_ratio: True
        pos_hint: {'center_x':0.7}

我觉得我需要对 on_press 语句做些什么,但我不太确定是什么。感谢任何帮助。

我在下面为您提供了一个示例,说明如何使用您所描述的 on_press 方法从按钮生成图像。通过使用工厂模块,您可以生成在 *.kv 文件中创建的模板。因此,要完成您的程序,您需要创建更多此类模板,然后使用条件在 on_press 方法中生成适当的图像模板。您也可以尝试在 Python 中创建动态模板,但我相信我的示例更简单。

test.py:

import kivy
kivy.require('2.0.0')

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout


class TestBoxLayout(BoxLayout):
    pass


class TestApp(App):
    def build(self):
        return TestBoxLayout()


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

test.kv:

#: import Factory kivy.factory.Factory


<TestImage@Image>:
    source: 'test.jpg'
    #allow_stretch: True
    #keep_ratio: True
    pos_hint: {'centre_X':0.7}


<TestBoxLayout>:
    orientation:'vertical'
    size: root.width,root.height
    font_size: 20
    padding: 100
    spacing: 10

    Button:
        text: 'press me'
        on_press: root.add_widget(Factory.TestImage())
        on_release: print("ahhh")
        on_state:
        #print("my current state is {}".format(self.state))
        size_hint: (0.3,0.3)

为了将此解决方案扩展到您的评论中,我在下面给出了进一步的示例。我想重申一下,我的示例旨在简单易懂,当然可以更有效地完成,但希望这可以作为您问题的明确解决方案。如果满足您的需求,请将此设为最佳答案!

test.kv:

#: import Factory kivy.factory.Factory


<TestImage1@Image>:
    source: 'test_1.jpg'
    #allow_stretch: True
    #keep_ratio: True
    pos_hint: {'centre_X':0.7}


<TestImage2@Image>:
    source: 'test_2.jpg'
    #allow_stretch: True
    #keep_ratio: True
    pos_hint: {'centre_X':0.7}


<TestBoxLayout>:
    orientation:'vertical'
    size: root.width,root.height
    font_size: 20
    padding: 100
    spacing: 10

    Slider:
        id: slider
        min: 1
        max: 2
        step: 1

    Button:
        text: 'press me'
        on_press: 
            if slider.value == 1: root.add_widget(Factory.TestImage1())
            elif slider.value == 2: root.add_widget(Factory.TestImage2())
        on_release: print("ahhh")
        on_state:
        #print("my current state is {}".format(self.state))
        size_hint: (0.3,0.3)