2016-09-18 80 views
0

新的kivy庫和動態更新屬性有一些麻煩。這裏的標籤只是一個地方持有人。最終,我希望顯示的圖像根據用戶點擊/觸摸哪個象限順序更改。動態更新kivy程序(Python)中的標籤文本

程序運行正常,沒有錯誤,懸停標籤(label2)不更新(label1更新)。當我點擊四象限時,象我期望的那樣,象限號碼顯示在控制檯上。我也打印出self.incr,無論用戶什麼時候點擊Q1,這也會顯示並增加,這意味着incr屬性正在增加。

所以,我不明白爲什麼它不更新標籤。

main.py

from kivy.app import App 
from kivy.uix.widget import Widget 
from kivy.uix.image import Image 

class TouchInput(Widget): 

    def __init__(self,**kwargs): 
     self.incr = 5 
     super(TouchInput,self).__init__(**kwargs) 

    def on_touch_up(self, touch): 

     if touch.x < self.width/2: 
      lateral = 'left' 
     elif touch.x > self.width/2: 
      lateral = 'right' 
     else: 
      lateral = None 

     if touch.y < self.height/2: 
      vertical = 'bottom' 
     elif touch.y > self.height/2: 
      vertical = 'top' 
     else: 
      vertical = None 

     if vertical and lateral: 
      if lateral == 'left' and vertical == 'top': 
       quadrant = 1 
       print 'Q1' 
       self.incr += 1 
       print self.incr 
      elif lateral == 'right' and vertical == 'top': 
       quadrant = 2 
       print 'Q2' 
      elif lateral == 'left' and vertical == 'bottom': 
       quadrant = 3 
       print 'Q3' 
      elif lateral == 'right' and vertical == 'bottom': 
       quadrant = 4 
       print 'Q4' 

class PPVT(App): 

    def build(self): 
     t = TouchInput() 
     print t.incr 
     return t 


if __name__ == "__main__": 
    PPVT().run() 

main.kv

<TouchInput>: 
    Image: 
     source: 'img1.jpg' 
     size: root.width, root.height 
    Label: 
     id: label1 
     text: str(root.width) 
     pos: root.width/2, root.height/2 
    Label: 
     id: label2 
     text: str(root.incr) 

回答

1

使用數字財產,所以kivy可以跟蹤它的變化。

from kivy.properties import NumericProperty 
... 
class TouchInput(Widget): 

    incr = NumericProperty(5) 
    ... 
+0

謝謝,這很好。我很好奇爲什麼我無法使用self.attr設置屬性,並且在它跟蹤self.width之類的事情時讓kivy保持跟蹤狀態? – Daniel

+1

@Daniel'self.width'是一個屬性,也可能是一個數字屬性。 – jligeza