所以我试图让我的小部件在播放器属性发生变化时更新。player 是一个 Player 对象。(大大)缩短的版本如下:
class Stats(Object):
def __init__(self, health, max_health):
self.health=health
self.max_health=max_health
class Player(Object):
def __init__(self, stats):
self.stats=stats
player= Player(Stats(50,100))
我的 kivy 根类是一个 BoxLayout,它有一个显示玩家健康状况的 ProgressBar。
class GameRoot(BoxLayout):
p= ObjectProperty(player)
def do_something(self):
self.p.stats.health-=5
每次按下回车键时都会调用 do_something(我已经检查过它是否有效)。这是 GameRoot 的 .kv 文件
GameRoot:
ProgressBar:
min:0
max:root.p.stats.max_health
value:root.p.stats.health
一切正常,除了当玩家的健康(或任何其他属性)改变时小部件不会更新。
对 GameRoot 的以下更改使其更新:
class GameRoot(BoxLayout):
phealth= ObjectProperty(player.stats.health)
p= ObjectProperty(player)
def do_something(self):
self.phealth-=5
GameRoot:
ProgressBar:
min:0
max:root.p.stats.max_health
value:root.phealth
但这并不是一个好的选择,因为 Player 和 Stats 都有很多实例变量,每当它们发生变化时我都需要更新它们。
我将不胜感激任何帮助。我环顾四周,但没有找到任何解决方案。
编辑:
当我将所有内容更改为属性时,当我尝试在函数中使用属性时会出错。
class Stats(EventDispatcher):
levels = ListProperty(levels)
health = NumericProperty()
xp = NumericProperty()
level = NumericProperty()
max_health = NumericProperty()
def __init__(self, **kwargs):
super().__init__(Stats, self).__init__(**kwargs)
def set_level(self):
for l in range(100):
if self.xp < self.levels[l]:
self.level= l-1
break
s= Stats
s.health=10
s.xp=500
s.set_level()
我收到以下错误:TypeError: set_level() missing 1 required positional argument: 'self'
在代码的其他区域,我收到错误消息说我不能将 NumericProperties 用作整数或 ListProperties 不可下标。
如果我遗漏了一些明显的东西,我深表歉意。我最近才开始使用 Kivy。