我有一个双屏kivy应用程序,我想使用python将变量从一个屏幕传递到第二个屏幕。
python文件
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import StringProperty,ObjectProperty
from kivy.uix.label import Label
class MenuScreen(Screen):
label1=StringProperty()
label2=StringProperty()
def __init__(self,**kwargs):
super(MenuScreen, self).__init__(**kwargs)
self.label1="hello"
self.label2="world"
def change_text(self):
lbl1=self.label1+ " and "
lbl2= "A beautiful "+self.label2
chg=SettingsScreen()
chg.UpdateSettings(lbl1,lbl2)
# HERE: something like
class SettingsScreen(Screen):
label3=StringProperty()
label4=StringProperty()
def __init__(self,**kwargs):
super(SettingsScreen, self).__init__(**kwargs)
#some default texts
self.label3="Nothing"
self.label4="Nothing"
def UpdateSettings(self,lbl1,lbl2):
print(lbl1,lbl2)
self.label3=lbl1
self.label4=lbl2
class TestScreenManager(ScreenManager):
menu_screen=ObjectProperty(None)
settings_screen=ObjectProperty(None)
class TestApp(App):
def build(self):
return TestScreenManager()
TestApp().run()
kvfile
#: import ScreenManager kivy.uix.screenmanager.ScreenManager
#: import Screen kivy.uix.screenmanager.ScreenManager
#: import SettingsScreen screen
<TestScreenManager>:
id: screen_manager
menu_screen: menu_screen
settings_screen: settings_screen
MenuScreen:
id: menu_screen
name: 'menu'
manager: screen_manager
SettingsScreen:
id: settings_screen
name: 'settings_screen'
manager: screen_manager
<MenuScreen>:
name: 'MenuScreen'
BoxLayout:
Label:
text:root.label1
Label:
text:root.label2
Button:
text: 'Goto nn'
size_hint_y:0.2
on_press:
root.manager.current = 'settings_screen'
root.change_text()
<SettingsScreen>:
#name: 'SettingsScreen'
label_id: label_field
BoxLayout:
Label:
text:root.label3
Label:
text:root.label4
Label:
id: label_field
text: "some text"
它运行没有错误,但它没有改变第二个屏幕的变量。为了进行调试,我在print(lbl1,lbl2)
函数中添加了UpdateSetting
,它打印出传递的lbl1和lbl2变量但不更新标签。
答案 0 :(得分:1)
执行chg=SettingsScreen()
后,您正在创建SettingsScreen
类的新实例,并修改该实例的标签。您需要访问ScreenManager使用的对象,而不是创建新对象。
您可以使用当前屏幕的manager
属性来获取另一个屏幕的实例引用:
def change_text(self):
lbl1=self.label1 + " and "
lbl2= "A beautiful "+ self.label2
chg = self.manager.settings_screen #<<<<<<<<<<<<<<
chg.UpdateSettings(lbl1,lbl2)