1
我有兩個屏幕kivy應用程序,我想使用python將變量從一個屏幕傳遞到第二個屏幕。在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"
它運行沒有錯誤,但它不改變第二屏幕的變量。爲了調試,我在UpdateSetting
函數中添加了print(lbl1,lbl2)
,並打印出傳遞lbl1和lbl2變量,但不更新標籤。