我想用简单的词将.kv文件中的函数绑定到.py文件中的方法,我想每天在应用程序的主屏幕上更新引号,因此我使用屏幕小部件显示引号,所以我该怎么办?将label.text绑定到.py文件中的方法 这是我要绑定的.py文件的类
class MainScreen(FloatLayout):
def quote(self):
self.quote.text = 'I often think that the night is more alive and more richly colored than
the day. - Vincent van Gogh'
这是.kv文件的根窗口小部件
<MainScreen>:
story: story
canvas:
Color:
rgba: 0, 0, 0, 1
Rectangle:
pos: self.pos
size: self.size
Label:
id: story
text: root.quote
font_size: '20sp'
size: self.texture_size
pos_hint: {'x': -0.2, 'y': 0.27}
但显示错误消息,提示label.text必须为字符串
答案 0 :(得分:0)
您可以使用奇异的Property
并使用quote()
方法来更新Property
。这是在代码中执行此操作的方法:
class MainScreen(FloatLayout):
quote_text = StringProperty('Not Set')
def quote(self, *args):
self.quote_text = 'I often think that the night is more alive and more richly colored than the day. - Vincent van Gogh'
quote_text
是可以在StringProperty
中引用的kv
,并且quote
方法现在更新了StringProperty
。
在您的kv
中:
<MainScreen>:
story: story
canvas:
Color:
rgba: 0, 0, 0, 1
Rectangle:
pos: self.pos
size: self.size
Label:
id: story
text: root.quote_text
font_size: '20sp'
size: self.texture_size
pos_hint: {'x': -0.2, 'y': 0.27}
然后,调用quote()
方法将更新Label
文本。要对其进行测试,可以使用build()
中的App
方法:
def build(self):
main = MainScreen()
Clock.schedule_once(main.quote, 5)
return main