[英]Why am I getting `'NoneType' object has no attribute` in .kv file?
我的簡化.kv
文件:
<GameWorld>:
player: the_player
canvas:
Rectangle:
pos: 5, root.top - 25
size: self.player.health, 20 # error raised in this line
Player:
id: the_player
center: self.center
我的簡化 Python 文件:
class Player(Widget):
health = NumericProperty(50)
def __init__(self, **kwargs):
super(Player, self).__init__(**kwargs)
self.health = 100
class GameWorld(Widget):
player = ObjectProperty()
entities = ListProperty()
def __init__(self, **kwargs):
super(GameWorld, self).__init__(**kwargs)
self.entities.append(self.player)
我得到的錯誤:
AttributeError: 'NoneType' object has no attribute 'health'
Kivy 認為self.player
是None
。 請幫助我理解出了什么問題。
當評估canvas
指令時, GameWorld.player
仍然是None
,這是ObjectProperty
的默認值,因此出現錯誤。
如果您將None
的測試添加到 kv 規則中,如下所示:
<GameWorld>:
player: the_player
canvas:
Rectangle:
pos: 5, root.top - 25
size: self.player is not None and self.player.health, 20
不會拋出錯誤,但不會執行自動綁定。 但是,如果您將rebind=True
添加到ObjectProperty
的聲明中:
class GameWorld(Widget):
player = ObjectProperty(rebind=True)
這將正常工作。
留下不太優雅的替代解決方案:
您可以在定義時實例化Player
對象:
class GameWorld(Widget):
player = ObjectProperty(Player())
或者,您可以向GameWorld
添加另一個NumericProperty
,其唯一目的是綁定到player.health
,但初始化為一個合理的值:
class GameWorld(Widget):
_player_health = NumericProperty(1)
和
<GameWorld>:
player: the_player
_player_health: the_player.health
canvas:
Rectangle:
pos: 5, root.top - 25
size: self._player_health, 20
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.