【问题标题】:How to reference widgets of different screens created in kivy using kv language?如何引用在 kivy 中使用 kv 语言创建的不同屏幕的小部件?
【发布时间】:2019-11-04 05:17:00
【问题描述】:

我的应用由 2 个屏幕组成:

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

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

按下按钮时,我想捕获在 Screen1 的 textinput 中输入的数据,并在 Screen2 的 textinput 中打印。

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

ma​​in.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】:

    通过txtinp1: textinp1,您表示 Screen1 通过 txtinp1 属性映射 textinp1 对象,但是您想通过 ScreenManager 的根访问该属性,这显然是错误的。

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多