kivy 中的文本标签未更新
Text Labels in kivy are not being updated
我正在尝试显示 Kivy 游戏中玩家剩余的尝试次数。然而,虽然玩家实际上可以 运行 尝试游戏中的次数,但剩余的尝试次数不会在 UI 中更新。我怀疑这是因为 Label 只显示一次,之后需要更新,或者可能与 Kivy ids 有关。
代码的简化版本在这里
在 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)
将你的尝试变量设置为kivy属性,然后kv语言在发生变化时会自动绑定更新:
from kivy.properties import NumericProperty
class TreasureHuntGrid(GridLayout):
attempts = NumericProperty(0)
...
我正在尝试显示 Kivy 游戏中玩家剩余的尝试次数。然而,虽然玩家实际上可以 运行 尝试游戏中的次数,但剩余的尝试次数不会在 UI 中更新。我怀疑这是因为 Label 只显示一次,之后需要更新,或者可能与 Kivy ids 有关。
代码的简化版本在这里
在 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)
将你的尝试变量设置为kivy属性,然后kv语言在发生变化时会自动绑定更新:
from kivy.properties import NumericProperty
class TreasureHuntGrid(GridLayout):
attempts = NumericProperty(0)
...