我相信我的问题是 ScreenManager:部分中的label_text标签在运行change_text()函数时未得到更新,因为它只显示了原始的label_text值。情况不算什么。
有人知道如何更新标签吗?我的目标是能够在2个Screen类之间传递字符串。因此,当用户在前一个屏幕上输入邮政编码时,我可以将其传递到新屏幕。
#:kivy 1.1.3
ScreenManager:
id: screen_manager
SearchScreen:
id: search_screen
name: 'SearchScreen'
manager: screen_manager
ForecastScreen:
id: forecast_screen
name: 'ForecastScreen'
manager: screen_manager
label_text: search_screen.text
<SearchScreen>:
display: entry
FloatLayout:
TextInput:
id: entry
on_text_validate:
root.change_text()
<ForecastScreen>:
BoxLayout:
FloatLayout:
Label:
text:root.label_text
然后输入py代码:
class SearchScreen(Screen):
text = StringProperty('')
def change_text(self):
self.text = "show this text"
self.manager.current = "ForecastScreen"
class ForecastScreen(Screen):
label_text = StringProperty()
Builder.load_file('weather.kv')
sm = ScreenManager()
sm.add_widget(SearchScreen(name='SearchScreen'))
sm.add_widget(ForecastScreen(name='ForecastScreen'))
class WeatherApp(App):
def build(self):
return sm
if __name__ == "__main__":
WeatherApp().run()
答案 0 :(得分:1)
首先,如果TextInput的multiline属性设置为False,则只有在按Enter时才会调用on_text_validate。
另一方面,我发现您不了解两者之间的区别:
Foo:
和
<Foo>:
在第一种情况下,您将创建Foo的实例(并且只能有一个这种类型的元素),在第二种情况下,您将实现组件。当您调用Builder.load_file()
并具有第一个不带“ <”“>”的元素时,即返回该实例,即已经有一个ScreenManager,但是对于您而言,您已经用python代码创建了另一个。在.kv中实例化的ScreenManager已经具有已链接文本的Screen,而在更改中,Python没有。当您返回使用python创建的ScreenManager时,如果没有链接的元素,您将观察到正确的行为,则不会进行任何修改。
您要做的是从.py中删除ScreenManager并使用.kv:
*。py
class SearchScreen(Screen):
text = StringProperty('')
def change_text(self):
self.text = "show this text"
self.manager.current = "ForecastScreen"
class ForecastScreen(Screen):
label_text = StringProperty("")
sm = Builder.load_file('weather.kv')
class WeatherApp(App):
def build(self):
return sm
if __name__ == "__main__":
WeatherApp().run()
*。kv
ScreenManager:
id: screen_manager
SearchScreen:
id: search_screen
name: 'SearchScreen'
ForecastScreen:
id: forecast_screen
name: 'ForecastScreen'
label_text: search_screen.text
<SearchScreen>:
display: entry
FloatLayout:
TextInput:
id: entry
multiline: False # <----
on_text_validate:
root.change_text()
<ForecastScreen>:
BoxLayout:
FloatLayout:
Label:
text: root.label_text