我使用来自First Screen
的输入,将该输入存储到全局变量CHOSEN_INPUT
中,然后当我转到Second Screen
时,该全局变量将显示在那里。
我已经有了开始,但不知道该去哪里。。。也许使用ObjectProperty
,但我不知道如何将它从一个类传递到另一个类。
global_test.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.screenmanager import Screen, ScreenManager, NoTransition
from kivy.properties import ObjectProperty
#global variable
CHOSEN_INPUT = ''
class FirstScreen(Screen):
obj_input = ObjectProperty()
obj_label = ObjectProperty()
obj_okay = ObjectProperty()
def buttonClicked(self):
global CHOSEN_INPUT
print('RESULT :', self.obj_input.text)
self.obj_label.text = "You wrote : " + self.obj_input.text
CHOSEN_INPUT = self.obj_input.text
class SecondScreen(Screen):
pass
class FromFirstScreen(BoxLayout):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
global CHOSEN_INPUT
self.orientation = 'vertical'
lbl = Label(Text=CHOSEN_INPUT)
self.add_widget(lbl)
class Global_VariableApp(App):
def build(self):
sm = ScreenManager(transition=NoTransition())
sm.add_widget(FirstScreen(name='firstcreen'))
sm.add_widget(SecondScreen(name='secondscreen'))
return sm
if __name__ == "__main__":
Global_VariableApp().run()
和:
global_variable.kv
<FirstScreen>:
obj_input: input_box
obj_label: label_box
obj_okay: okay_btn
BoxLayout:
orientation: 'vertical'
TextInput:
id: input_box
size_hint_y: None
height: "40dp"
multiline: False
Label:
id: label_box
Button:
id: okay_btn
text: "Okay"
on_press: root.buttonClicked()
Button:
text: "Go To Second Screen"
on_press: root.manager.current = 'secondscreen'
<SecondScreen>:
BoxLayout:
orientation: 'vertical'
Button:
text: "Input from First Screen :"
FromFirstScreen:
Button:
text: "Go To First Screen"
on_press: root.manager.current = 'firstcreen'
得益于@mcastle的解决方案:从另一个小部件更改Kivy小部件属性
我在类SecondScreen
中放入了一个update_text
函数:
class SecondScreen(Screen):
obj_input1_box = ObjectProperty()
def update_text(self, label_text):
#print('label_text :', label_text)
self.obj_input1_box.text = label_text
在kv文件中,我插入了一个函数:root.manager.get_screen('secondscreen').update_text(root.obj_label.text)
(并为更新的SecondScreen
的文本标签放一个id
):
<FirstScreen>:
...
Button:
id: okay_btn
text: "Okay"
on_press: root.buttonClicked(); root.manager.get_screen('secondscreen').update_text(root.obj_label.text) ...
<SecondScreen>:
obj_input1_box: input1_box
...
Label:
id: input1_box
...