[英]How do you pass a variable between screens in Kivy?
Here is my code:这是我的代码:
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()
I am attempting to instantiate a new screen by the click of a button in another screen.我试图通过单击另一个屏幕中的按钮来实例化一个新屏幕。 That in and of itself works flawlessly.
这本身就完美无缺。 The other thing I'm trying to do is pass a variable to that screen for use with methods I will be writing later on.
我正在尝试做的另一件事是将变量传递给该屏幕,以便与我稍后将要编写的方法一起使用。 In this sample here I am simply passing a string, Whenever I attempt to run this, after clicking the button in screen one: I get the following error:
AttributeError: 'ScreenTwo' object has no attribute 'text'
在此示例中,我只是传递一个字符串,每当我尝试运行它时,在单击屏幕一中的按钮后:我收到以下错误:
AttributeError: 'ScreenTwo' object has no attribute 'text'
How can I get around this and successfully pass a variable between screens?我怎样才能解决这个问题并成功地在屏幕之间传递一个变量?
Create a StringProperty
for the attribute text
and pass it to ScreenTwo
as a kwarg.为属性
text
创建一个StringProperty
并将其作为 kwarg 传递给ScreenTwo
。
class ScreenTwo(Screen):
text = StringProperty("")
class WindowManager(ScreenManager):
def load_screen_two(self, text):
self.add_widget(ScreenTwo(text = text))
However, is the following a typing error or it is actually there in the original code?但是,以下是输入错误还是实际上存在于原始代码中? If the latter is the case here, the indentations should be consistent.
如果这里是后者,则缩进应该是一致的。
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.