如何引用使用kv语言在kivy中创建的不同屏幕的窗口小部件?

问题描述 投票:1回答:1

我的应用包含2个屏幕:

屏幕1-1文本输入小部件和1按钮小部件

屏幕2-1文本输入窗口小部件

按下按钮时,我要捕获在屏幕1的文本输入中输入的数据并在屏幕2的文本输入中打印。

我尝试了以下代码,但出现错误:

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中寻找解决方案,但找不到。

python-3.x kivy kivy-language
1个回答
1
投票

[通过执行txtinp1: textinp1,您表示Screen1通过txtinp1属性映射了textinp1对象,但随后您希望通过作为ScreenManager的根来访问该属性,这显然是错误的。

有很多解决方案,但在这种情况下,我将展示如何在ScreenManager中映射每个Screen的属性:

WindowManager:
    txtinp1: screen1.textinp1
    txtinp2: screen2.textinp2
    Screen1: 
        id: screen1       
    Screen2:
        id: screen2


 &ltScreen1>    
    textinp1: textinp1
    name:'main'
    GridLayout:
        cols:1        
        TextInput:
            id:textinp1
        Button:
            text:'Submit'
            on_press: 
                app.root.current = 'second'
                app.disp()

 &ltScreen2>
    textinp2: textinp2
    name:'second'
    GridLayout:        
        cols:1        
        TextInput:
            id:textinp2
© www.soinside.com 2019 - 2024. All rights reserved.