2015-12-11 62 views
0

我想顯示Kivy遊戲中玩家留下的嘗試次數。然而,雖然玩家可以在遊戲中實際嘗試用完,但剩下的嘗試不會在UI中更新。我懷疑這是因爲該標籤只顯示一次,需要更新後或者可能與Kivy ID有關。kivy中的文本標籤沒有更新

代碼的簡化版本在這裏

在main.py我們:

class TreasureHuntGrid(GridLayout): 
    attempts = 8 
    board = [[0,0][0,0]] 
    def __init__(self, *args, **kwargs): 
     super(TreasureHuntGrid, self).__init__(*args, **kwargs) 

    def lowerattempts(self, button): 
     if condition: 
      self.attempts = self.attempts - 1 

在.kv文件有:

AnchorLayout: 
    anchor_y: 'bottom' 
    anchor_x: 'left' 
    TreasureHuntGrid: 
    id: board 
    size: min(self.parent.size), min(self.parent.size) 
    size_hint: None, None 
    Label: 
    size_hint: (1.75, 1) 
    height: sp(40) 
    text:'You have {} attempts left'.format(board.attempts) 

回答

1

讓你嘗試的變量一個kivy屬性,那麼kv語言會自動綁定更新,當它發生變化時:

from kivy.properties import NumericProperty 

class TreasureHuntGrid(GridLayout): 
    attempts = NumericProperty(0) 
    ...