2015-05-27 352 views
0

我目前正在使用Kivy和Python的一些代碼。我試圖做到這一點,當你點擊一個按鈕,按鈕的文字顏色會改變。Kivy顏色隨着按鈕變化

當我點擊按鈕,但是,顏色不喜歡我想要的。

任何想法如何解決這個問題?我只是在學習基維,也許答案比我想的要容易。該.py文件低於

from kivy.app import App 
from kivy.uix.widget import Widget 
from kivy.properties import ObjectProperty 
from kivy.uix.button import Button 
from kivy.graphics import Color 
class TextBubbleSample(Widget): 
    bubble = ObjectProperty(None) 

class TextBubble(Widget): 
     pass 

class Talk(Button): 
    btn = Button 
    def button_press(self): 
     btn.bind(on_state = self.on_event) 

def on_event(self): 
     btn.color = 1,0,0,1 

class TextBubbleApp(App): 
    def build(self): 
     return TextBubbleSample() 

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




and here is the .kv file 

#:kivy 1.0.9 

<TextBubbleSample>: 
    bubble: text_bubble 
    btn: click_here 

    TextBubble: 
     id: text_bubble 
     x: root.x 
     center_y: root.center_y 

    Talk: 
     id: click_here 
     x: 10 
     center_y: 220 
     text: "Talk to me." 
     color: 0,0,1,1 

<TextBubble>: 
    canvas: 
     Color: 
      rgba: 1,0,0,1 
     Rectangle: 
      pos: 10, 10 
      size: 780, 150 

    Label: 
     color: 0,0,1,1 
     font_size: 35 
     center_x: 200 
     top: root.top - 200 
     text: "I am talking" 

回答

1

你不應該/不能使用變量btn這樣。使用self.bind(on_state=self.on_event)然後self.color = (1, 0, 0, 1)

0

你應該儘量減少代碼長度,在這種情況下你不需要使用任何id。

對於惡意的答案可能有一個簡單的選擇。 在你的.py文件(Talk類)中添加。

class Talk(Button): 
.... 
def on_release(self): 
    self.color = 1,0,0,1 

,並在您.kv文件中添加

Talk: 
    text: "talk to me" 
    .... 
    on_release: self.on_release 

編輯:

,你可以這樣來做太

class Singularity(BoxLayout): 
    def __init__(self,**kwargs): 
     super(Singularity,self).__init__(**kwargs) 
     self.b = Button(text = "hello",on_press = self.on_press) 
     self.add_widget(self.b) 
    def on_press(self,event): 
     if event.color == [1,0,0,1]: 
      event.color = [0,0,1,1] 
     else: 
      event.color=[1,0,0,1] 
+0

謝謝。這工作!現在我試圖改變顏色,如果你再次點擊按鈕。我嘗試了一種條件,如果self.color是一種顏色,並按下按鈕,它將切換到另一種顏色,如果self.color是另一種顏色,並且按下按鈕,則會切換回第一種顏色,但條件不工作。我知道我的語法正確,我沒有收到任何錯誤消息。我不知道怎麼回事...... – user4531234

+0

'if self.ids.p.color == [1,0,0,1]:self.ids.p.color = [1,1,0,1] else : self.ids.p.color = [1,0,0,1]'** p是id如果按鈕** – kiok46