Skip to content Skip to sidebar Skip to footer

How Do I Load An Image Into A Kivy Window Using A Button?

I am trying to use kivy with Python to develop a quick app with sliders where one has to use the sliders first to determine a setting and then click a 'Submit' which then loads the

Solution 1:

I have given you an example below of how to generate an image from a button using the on_press method as you have described. By using the factory module, you can generate templates created in your *.kv files. So to complete your program, you would create more of these templates, and then generate the appropriate image template in your on_press method using conditionals. You could alternatively try to create dynamic templates within Python, but I believe my example to be more simple.

test.py:

import kivy
kivy.require('2.0.0')

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


classTestBoxLayout(BoxLayout):
    passclassTestApp(App):
    defbuild(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: Truepos_hint: {'centre_X':0.7}


<TestBoxLayout>:orientation:'vertical'size:root.width,root.heightfont_size:20padding:100spacing:10Button: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)

To extend this solution to your comment, I have given a further example below. I want to reiterate that my example is designed to be simple to understand and can certainly be done more efficiently, but hopefully this acts as a clear solution to your problem. Please mark this as the best answer if this fulfils your needs!

test.kv:

#: import Factory kivy.factory.Factory<TestImage1@Image>:source:'test_1.jpg'#allow_stretch: True#keep_ratio: Truepos_hint: {'centre_X':0.7}


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


<TestBoxLayout>:orientation:'vertical'size:root.width,root.heightfont_size:20padding:100spacing:10Slider:id:slidermin:1max:2step:1Button:text:'press me'on_press:ifslider.value==1:root.add_widget(Factory.TestImage1())elifslider.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)

Post a Comment for "How Do I Load An Image Into A Kivy Window Using A Button?"