如何仅使用Kivy的.kv语言将文本输入内容传递至多页面
问题描述
我当前的程序仅能将MainPage中Text Input的内容传递至本页面的Label组件,希望仅通过Kivy的.kv语言,实现将该Text Input的内容同步到多个页面各自对应的Label组件,是否有可行方案?
解决方案
可以通过Kivy内置的app.root(访问ScreenManager实例)结合屏幕名称获取其他页面的控件,实现文本同步,有两种简洁的实现方式:
方式1:实时事件同步
在MainPage的TextInput的on_text事件中,同时更新所有目标页面的Label文本,输入时所有页面的Label会实时变化:
修改TestFunction2.kv中MainPage的TextInput部分:
TextInput: id: my_text_input text: "" size_hint: .2, .05 pos_hint: {"x": .4, "y": .06} multiline: False # 文本变化时同步更新当前页面和Interior页面的Label on_text: root.ids.my_label.text = self.text app.root.get_screen("Interior").ids.my_label.text = self.text
方式2:属性绑定(推荐)
直接将其他页面的Label的text属性绑定到MainPage的TextInput的text,无需额外事件,切换页面时Label会自动显示最新内容:
修改TestFunction2.kv中Interior页面的Label部分:
Label: id: my_label # 绑定到MainPage的TextInput文本,为空时显示默认值 text: app.root.get_screen("MainPage").ids.my_text_input.text if app.root.get_screen("MainPage").ids.my_text_input.text else "-----" color: 0,1,0,1 size_hint: .2, None height: "60dp" pos_hint: {"center_x": .5, "y": .72}
完整修改后的kv代码
WindowManager: MainPage: Interior: <MainPage>: name: "MainPage" BoxLayout: orientation: "horizontal" size: root.width, root.height Button: text: "Main" color: 0,1,0,1 size_hint: .2, None height: "60dp" pos_hint: {"x": .2, "y": .9} font_size: "15dp" on_release: app.root.current = "MainPage" Button: text: "Interior" color: 0,1,0,1 size_hint: .2, None height: "60dp" pos_hint: {"x": .2, "y": .9} font_size: "15dp" on_release: app.root.current = "Interior" TextInput: id: my_text_input text: "" size_hint: .2, .05 pos_hint: {"x": .4, "y": .06} multiline: False # 可选:保留当前页面的实时更新,或者用方式2的绑定即可 on_text: root.ids.my_label.text = self.text Label: id: my_label text: my_text_input.text if my_text_input.text else "-----" color: 0,1,0,1 size_hint: .2, None height: "60dp" pos_hint: {"center_x": .5, "y": .72} Label: text: "Go 2 Green Installation App" color: 0,1,0,1 size_hint: .2, None height: "60dp" pos_hint: {"center_x": .5, "y": .8} <Interior>: name: "Interior" BoxLayout: orientation: "horizontal" size: root.width, root.height Button: text: "Main" color: 0,1,0,1 size_hint: .2, None height: "60dp" pos_hint: {"x": .2, "y": .9} font_size: "15dp" on_release: app.root.current = "MainPage" Button: text: "Interior" color: 0,1,0,1 size_hint: .2, None height: "60dp" pos_hint: {"x": .2, "y": .9} font_size: "15dp" on_release: app.root.current = "Interior" Label: id: my_label text: app.root.get_screen("MainPage").ids.my_text_input.text if app.root.get_screen("MainPage").ids.my_text_input.text else "-----" color: 0,1,0,1 size_hint: .2, None height: "60dp" pos_hint: {"center_x": .5, "y": .72}
内容的提问来源于stack exchange,提问作者Pete Simchuk
相关产品推荐
相关产品推荐

