2017-11-25 137 views
1

我從這裏得到了一個有用的用戶代碼,它幾乎是完美的。如何將兩個不同的gif綁定到kivy中的切換按鈕?

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的GIF POWER_ON時,它的切換上,當它切換關閉POWER_OFF GIF。所以我試圖將其更改爲切換按鈕,並添加了

on_press: gif.source="power_off.gif" 

但這並沒有奏效。它甚至從未玩過power_on gif,因爲它立即將gif的源碼更改爲power_off

這樣做的正確方法是什麼?

回答

1

以下承認第一GIF是power_off.gif

- 考慮添加StringProperty進口,該屬性將保持當前的GIF圖像源

from kivy.properties import StringProperty 

-Add處理不同變化的方法:

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' 

- 那麼你千伏添加這些變化:

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 


""") 
相關問題