我从这里的一个有用的用户那里得到了这个代码,它几乎是完美的。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
Builder.load_string("""
<ExampleApp>:
id: main
orientation: "vertical"
Button:
size_hint_x: None
size_hint_y: None
height: 300
width: self.height
center: self.parent.center
text: ""
on_press: gif.anim_delay = 0.09
on_press: gif._coreimage.anim_reset(True)
Image:
id: gif
source: 'power_on.gif'
center: self.parent.center
height: 300
width: self.height
allow_stretch: True
anim_delay: -1
anim_loop: 1
""")
class ExampleApp(App, BoxLayout):
def build(self):
return self
if __name__ == "__main__":
ExampleApp().run()
我需要它使用两个不同的gif,当它切换时,power_on gif和power_off gif,当它切换为关闭时。所以我尝试将其更改为切换按钮并添加
on_press: gif.source="power_off.gif"
但那根本不起作用。它甚至从未播放power_on gif,因为它立即将gif的源更改为power_off
这样做的正确方法是什么?
答案 0 :(得分:1)
以下承认第一个gif是power_off.gif
:
-consider添加StringProperty
导入,该属性将保留当前的gif图像源
from kivy.properties import StringProperty
- 添加一个方法来处理不同的变化:
class ExampleApp(App, BoxLayout):
power = StringProperty('power_off.gif')
def build(self):
return self
def change_state(self):
if self.power == 'power_on.gif':
self.power = 'power_off.gif'
else:
self.power = 'power_on.gif'
- 然后在你的kv中添加这些更改:
Builder.load_string("""
<ExampleApp>:
id: main
orientation: "vertical"
Button:
size_hint_x: None
size_hint_y: None
height: 300
width: self.height
center: self.parent.center
text: ""
on_press: gif.anim_delay = 0.09
on_press: gif._coreimage.anim_reset(True); root.change_state()
Image:
id: gif
source: root.power
center: self.parent.center
height: 300
width: self.height
allow_stretch: True
anim_delay: -1
anim_loop: 1
""")