我的应用程序由 2 个屏幕组成:
屏幕 1 - 1 个文本输入小部件和 1 个按钮小部件
屏幕 2 - 1 文本输入小部件
按下按钮时,我想捕获在 Screen1 的文本输入中输入的数据,并将其打印在 Screen2 的文本输入中。
我尝试了以下代码,但出现错误:
main.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
class Screen1(Screen):
pass
class Screen2(Screen):
pass
class WindowManager(ScreenManager):
txtinp1 = ObjectProperty(None)
txtinp2 = ObjectProperty(None)
class ResultsApp(App):
def build(self):
return Builder.load_file("tutorials\Design3.kv")
def disp(self):
self.root.txtinp2.text = self.root.txtinp1.text
if __name__ == "__main__":
ResultsApp().run()
design3.kv
WindowManager:
Screen1:
Screen2:
<Screen1>
name:'main'
txtinp1:textinp1
GridLayout:
cols:1
TextInput:
id:textinp1
Button:
text:'Submit'
on_press:
app.root.current = 'second'
app.disp()
<Screen2>
name:'second'
txtinp2:textinp2
GridLayout:
cols:1
TextInput:
id:textinp2
我收到的错误如下。
File "c:/Users/pavan m sunder/projects/kivy/tutorials/tut7(kvlang).py", line 25, in disp
self.root.txtinp2.text = self.root.txtinp1.text
AttributeError: 'NoneType' object has no attribute 'text'
我尝试在 stackoverflow 中寻找解决方案,但找不到。
最佳答案
通过执行 txtinp1: textinp1
,您表明 Screen1 通过 txtinp1 属性映射 textinp1 对象,但随后您希望通过根(即 ScreenManager)访问该属性,这显然是错误的。
有很多解决方案,但在本例中我将展示如何在 ScreenManager 中映射每个屏幕的属性:
WindowManager:
<b>txtinp1: screen1.textinp1
txtinp2: screen2.textinp2
Screen1:
id: screen1
Screen2:
id: screen2</b>
<Screen1>
textinp1: textinp1
name:'main'
GridLayout:
cols:1
TextInput:
id:textinp1
Button:
text:'Submit'
on_press:
app.root.current = 'second'
app.disp()
<Screen2>
textinp2: textinp2
name:'second'
GridLayout:
cols:1
TextInput:
id:textinp2
关于python-3.x - 如何使用kv语言引用kivy中创建的不同屏幕的小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58687551/