kivy:全局变量和 ScreenManager
Posted
技术标签:
【中文标题】kivy:全局变量和 ScreenManager【英文标题】:kivy: Global variable and ScreenManager 【发布时间】:2015-05-01 17:57:52 【问题描述】:我正在使用来自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'
【问题讨论】:
【参考方案1】:感谢@mcastle 的解决方案:Changing Kivy widget attribute from another widget
我已经在 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
...
【讨论】:
以上是关于kivy:全局变量和 ScreenManager的主要内容,如果未能解决你的问题,请参考以下文章
Kivy - Kv - ScreenManager - 改变当前屏幕
在 Kivy 1.10 和 Python 2.7.9 中使用 ScreenManager 获取 TextInput 值
Kivy ScreenManager 打破 BoxLayout