有没有办法通过 App class 将文本字段值分配给变量

Is there any way to assign text field value to a variable through the App class

我想通过应用程序将一个kivy文本字段值赋给一个变量class

这种情况有点不同,因为文本字段放置在注册为 Factory 小部件的框布局内

这是代码


from kivymd.app import App
from kivy.lang import Builder
from kivy.factory import Factory 

kv='''
#:import Factory kivy.factory.Factory

# this is object 1 which will be added to main grid

<object_1@BoxLayout>:

    orientation:'vertical'
    size_hint_y:None
    adaptive_height: True
    height:self.minimum_height 
    id:obj_1

    TextInput:
        size_hint:None,None 
        id:txt



#main grid

BoxLayout:
    orientation:'vertical'
    size_hint_y:None
    adaptive_height: True
    height:self.minimum_height 

    GridLayout:
        cols:1
        size_hint_y:None 
        adaptive_height:True
        height:self.minimum_height 
        id:sc_grid          
        Button:
            size_hint:None,None 
            text: 'Add 1'
            on_press:
                app.add_1()          
                    
        Button:
            size_hint:None,None 
            text: 'Assign value'
            on_press:
                app.Assign()                
                
'''

class MyApp(App):
    
    def build(self):
        return Builder.load_string(kv)

    
    def add_1(self):
        self.root.ids.sc_grid.add_widget(Factory.object_1())

    # this crashes

    def Assign(self):
        txt_1=self.root.ids.txt.text
        
MyApp().run()

我之前问过类似的问题,但没有得到任何合适的答案,所以我决定上传一个更清楚的答案

在上面的代码中

●按下按钮 Add1 , 包含文本字段的工厂小部件 (BoxLayout) 已添加到主布局

●我还创建了另一个按钮 'Assign value' 以将值分配给变量

我希望通过应用 class 本身分配它

您可以完全自由地进行任何修改,因为我只需要它背后的逻辑

提前致谢

kv 中定义的 ids 仅添加到作为定义 id 的规则根的小部件的 ids 字典中。因此 txt id 将不会出现在 BoxLayout 中,即 App 的根小部件。 id 只会出现在 object_1 实例的 ids 中。所以你可能需要保存对添加的 object_1 的引用,像这样:

def add_1(self):
    self.obj_1 = Factory.object_1()
    self.root.ids.sc_grid.add_widget(self.obj_1)

然后您可以像这样访问 txt id

def Assign(self):
    txt_1=self.obj_1.ids.txt.text

当然,如果 add_1() 方法被多次调用,您将只能引用最后添加的 object_1.

另一方面,kv 中使用的任何 class 名称都应大写。否则可能会导致语法错误。因此,您应该将 object_1 重命名为 Object_1.