问题描述
我目前遇到的问题是,一旦我单击接收来自滑块的输入的某个按钮(因此基本上该按钮会为给定的滑块值添加不同的图像),我想将图像添加到我的 kivy 应用程序中。我现在的问题是,我当前的解决方案使用 add_widget 命令,这显然会导致每次单击按钮时都会添加一个新的小部件。我想要的是,更新现有小部件而不是添加新小部件。
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)
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()
编辑:这是我上一个问题的解决方案的扩展:How do I load an image into a kivy window using a button?
解决方法
<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: img.source = 'test_1.jpg' if slider.value == 1 else 'test_2.jpg'
size_hint: (0.3,0.3)
Image:
id: img
color: (0,0) if self.source is None else (1,1,1)
pos_hint: {'centre_X':0.7}