【发布时间】:2015-04-18 02:50:13
【问题描述】:
我已经尝试让我的标签自动更新很长一段时间了,我已经阅读了十几个 StackOverflow 问题,但无济于事。
我有一个全局对象,其中包含一个整数值,我希望在其中一个小部件类中显示该值并带有标签。
小部件类如下所示:
class Battle(Widget):
def __init__(self, **kwargs):
super(Battle, self).__init__(**kwargs)
#Enemy Stats
self.enemyBar = BoxLayout(orientation="horizontal", size=(Window.width, Window.height/8), center_y = Window.height - self.height/2)
self.enemyBar.add_widget(Label(text=enemy.name))
#Enemy Health Label
health_label = Label(text=str(enemy.health))
self.enemyBar.add_widget(health_label)
self.add_widget(self.enemyBar)
def update_health(instance, value):
health_label.text = str(enemy.health) #<-- Error happens here
enemy.bind(health=update_health)
当enemy.health 的值在程序中改变时,我希望我的标签也改变。我不想使用任何 kivy 语言,因为我更喜欢只有一个主 python 文件。
敌人对象是使用实体类创建的。这是实体代码:
class entity(Widget):
#entity creation
health = NumericProperty()
def __init__(self, health):
self.health = health
当我运行代码时,我按下一个按钮,该按钮调用一个改变敌人生命值的函数,然后我得到一个错误:
未定义全局名称“health_label”
不知何故,当调用 update_health 函数时,程序看不到在 init 中创建的 health_label 变量。
【问题讨论】:
-
我通过将 health_label 变量设为全局变量来解决问题,现在这是我获得所需结果的唯一方法。
标签: python properties label kivy