[英]How do you pass a variable between screens in Kivy?
这是我的代码:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
build = f"""
WindowManager:
ScreenOne:
<ScreenOne>:
name: 'one'
BoxLayout:
orientation: 'horizontal'
size: root.width, root.height
Button:
text: 'Load Screen Two'
on_release:
on_press: app.root.load_screen_two('Screen Two')
on_release: Factory.NewGame().open()
app.root.current = 'two'
<ScreenTwo>:
name: 'two'
BoxLayout:
orientation: 'horizontal'
size: root.width, root.height
Label:
text: root.text
"""
class ScreenOne(Screen):
pass
class ScreenTwo(Screen):
def __init__(self, text, **kw):
super().__init__(**kw)
self.text = text
class WindowManager(ScreenManager):
def load_screen_two(self, text):
self.add_widget(ScreenTwo(text))
class Application(App):
def build(self):
return Builder.load_string(build)
if __name__ == '__main__':
Application().run()
我试图通过单击另一个屏幕中的按钮来实例化一个新屏幕。 这本身就完美无缺。 我正在尝试做的另一件事是将变量传递给该屏幕,以便与我稍后将要编写的方法一起使用。 在此示例中,我只是传递一个字符串,每当我尝试运行它时,在单击屏幕一中的按钮后:我收到以下错误: AttributeError: 'ScreenTwo' object has no attribute 'text'
我怎样才能解决这个问题并成功地在屏幕之间传递一个变量?
为属性text
创建一个StringProperty
并将其作为 kwarg 传递给ScreenTwo
。
class ScreenTwo(Screen):
text = StringProperty("")
class WindowManager(ScreenManager):
def load_screen_two(self, text):
self.add_widget(ScreenTwo(text = text))
但是,以下是输入错误还是实际上存在于原始代码中? 如果这里是后者,则缩进应该是一致的。
Button:
text: 'Load Screen Two'
on_release:
on_press: app.root.load_screen_two('Screen Two')
on_release: Factory.NewGame().open()
app.root.current = 'two'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.