使用Kivy Screen Manager,我创建了两个Screens.在屏幕1中,我想在屏幕2中更改标签.我在我的代码中突出显示了有问题的区域:
我的test.ky:
#: import ScreenManager kivy.uix.screenmanager.ScreenManager #: import Screen kivy.uix.screenmanager.ScreenManager #: import SettingsScreen screen ScreenManager: MenuScreen: SettingsScreen: <MenuScreen>: name: 'MenuScreen' BoxLayout: Button: text: 'Goto nn' on_press: root.manager.current = 'SettingsScreen' root.change_text() <SettingsScreen>: name: 'SettingsScreen' label_id: label_field BoxLayout: Label: id: label_field text: "to_be_changed"
和我的screen.py
from kivy.app import App from kivy.uix.Boxlayout import BoxLayout from kivy.uix.screenmanager import ScreenManager,Screen class MenuScreen(Screen): def change_text(self): pass # HERE: something like # root.SettingsScreen.label_field.text = 'new text' class SettingsScreen(Screen): pass class TestApp(App): pass TestApp().run()
任何帮助是极大的赞赏!
谢谢,尼科
解决方法
这个怎么样:
当您按下MenuScreen上的按钮时,它会在其自身上设置一个属性,其中包含您要放入SettingsScreen标签中的文本.然后在菜单屏幕中为kv文件分配一个id值,该值用于引用此属性.例:
main.py
class MenuScreen(Screen): text = StringProperty('') def change_text(self): self.text = "The text you want to set" self.manager.current = "SettingsScreen" class SettingsScreen(Screen): label_text = StringProperty('')
kv文件
ScreenManager: id: screen_manager MenuScreen: id: menu_screen name: 'MenuScreen' manager: screen_manager SettingsScreen: name: 'SettingsScreen' manager: screen_manager label_text: menu_screen.text <MenuScreen>: BoxLayout: Button: text: 'Goto nn' on_press: root.change_text() <SettingsScreen>: BoxLayout: Label: text: root.label_text