我的问题是,在我在一个屏幕上设置变量之后如何在另一个屏幕上调用它?
以下是我要做的事情的代码:
main.py
import kivy
kivy.require('1.10.0')
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
class Manager(ScreenManager):
pass
class FirstScreen(Screen):
pass
class SecondScreen(Screen):
pass
class ExampleApp(App):
def build(self):
return Manager()
if __name__ == '__main__':
ExampleApp().run()
example.kv
#: import sm kivy.uix.screenmanager
#: set Question 'not working'
<Manager>
transition: sm.FadeTransition()
FirstScreen:
SecondScreen:
<FirstScreen>
BoxLayout:
TextInput:
id: txt
multiline: False
Button:
text: 'Press Me'
on_release:
Question = txt.text
app.root.current = 'Next'
<SecondScreen>
name: 'Next'
Label:
text: Question
当它运行时,一切正常。有一个例外。 SecondScreen上的标签显示&#34;不工作&#34;何时应该读取我在FirstScreen上的文本输入中键入的内容。为什么我不能完成这项任务?
答案 0 :(得分:1)
您必须提供id标记并使用ids方法或ObjectProperty来引用变量。有关详细信息,请参阅下面的两个示例。
id是小部件的弱参数。
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
class Manager(ScreenManager):
pass
class FirstScreen(Screen):
pass
class SecondScreen(Screen):
pass
class ExampleApp(App):
def build(self):
return Manager()
if __name__ == '__main__':
ExampleApp().run()
#:kivy 1.10.0
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
#: set Question 'not working'
<Manager>
transition: FadeTransition()
FirstScreen:
SecondScreen:
id: second_screen
<FirstScreen>
BoxLayout:
TextInput:
id: txt
text: "Working!"
multiline: False
Button:
text: 'Press Me'
on_release:
root.manager.ids.second_screen.ids.label.text = txt.text
app.root.current = 'Next'
<SecondScreen>
name: 'Next'
Label:
id: label
text: Question
使用ObjectProperty的“最佳实践”。这样可以创建直接引用,提供更快的访问速度,并且更加明确。
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.properties import ObjectProperty
class Manager(ScreenManager):
second_screen = ObjectProperty()
class FirstScreen(Screen):
pass
class SecondScreen(Screen):
label = ObjectProperty()
class ObjectPropertyApp(App):
def build(self):
return Manager()
if __name__ == '__main__':
ObjectPropertyApp().run()
#:kivy 1.10.0
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
#: set Question 'not working'
<Manager>
second_screen: second_screen
transition: FadeTransition()
FirstScreen:
SecondScreen:
id: second_screen
<FirstScreen>
BoxLayout:
TextInput:
id: txt
text: "Working!"
multiline: False
Button:
text: 'Press Me'
on_release:
root.manager.second_screen.label.text = txt.text
app.root.current = 'Next'
<SecondScreen>
name: 'Next'
label: label
Label:
id: label
text: Question