Kivy属性以及不同小部件和布局类之间的通信

时间:2019-01-02 12:28:38

标签: python kivy

我在下面有一个简单的问题示例。我有三个类MyLayout(根),弹出一个弹出类和MyBox,这是一个通过单击MyLayout中的按钮动态创建的Boxlayout。我已经在与弹出字段一起使用的根目录中创建了capitalise()函数。我的问题是与MyBox实例的交互。例如,弹出窗口如何才能知道哪个MyBox调用了它,并将名字和姓氏返回到适当的TextInput框中?

如果我想整理所有MyBox实例中TextInput框中的所有数据,我该怎么做。我假设使用属性。

预先感谢

String

1 个答案:

答案 0 :(得分:0)

您想要的主要事情是将“创建者”框的引用传递给“创建的”弹出窗口。您可以通过在创建时间on_press: Factory.Pop(root).open()

传递窗口小部件来实现

此处提供完整的工作代码:

Builder.load_string('''
#:import Factory kivy.factory.Factory
<MyBox>:
    orientation:'vertical'
    TextInput:
        text: root.box_text # bind the text to the box_text
    Button:
        text: 'Choose a name'
        on_press: Factory.Pop(root).open()  # pass the creator of the pop here

<Pop>:
    auto_dismiss: False
    title: 'Names'
    size_hint: [0.4, 0.5]
    pos_hint:{'right': 0.4, 'top': 1}
    id: msg_box
    GridLayout:
        id: _pop
        rows: 3
        GridLayout:
            id: pop_grid
            cols:2
            padding: [0,5]
            Spinner:
                text: 'First Name'
                id: fn
                sync_height: True
                values: ['andrew', 'brian', 'colin', 'david', 'edmond']
                width: self.width
                on_text: self.text = app.root.capitalise(self.text)
            Spinner:
                text: 'Last Name'
                id: ln
                sync_height: True
                values: ['Adams', 'Bass', 'Carney', 'Davies', 'Edmonds']
                width: self.width


        Button:
            padding: [0,5]
            text: 'OK'
            on_release:
                root.creator.box_text = "{} {}".format(fn.text, ln.text)  # use the creator reference
                root.dismiss()
            width: self.width

<MyLayout>:
    orientation: 'tb-lr'
    size_hint: .2, 0.5
    width: self.width
    Button:
        text: 'Create name box.'
        on_press: app.root.make_name_box()
        width: 300
''')


class MyLayout(StackLayout):
    pass

    def make_name_box(self):
        self.add_widget(MyBox())

    def capitalise(self, text):
        return text.capitalize()


class Pop(Popup):
    def __init__(self, creator, **kwargs):
        super(Pop, self).__init__(**kwargs)
        self.creator = creator # keep a reference to the creator here


class MyBox(BoxLayout):
    box_text = StringProperty("N/A")

    def __init__(self, **kwargs):
        super(MyBox, self).__init__(**kwargs)
        size_hint = None, None
        width = 300


class PopperApp(App):
    def build(self):
        self.my_layout = MyLayout()
        return self.my_layout

    def on_stop(self):  # print the names when leaving the app
        boxes = self.my_layout.children[:-1]
        print([i.box_text for i in boxes])


if __name__ == '__main__':
    PopperApp().run()

编辑:关于第二个问题,我在关闭应用程序时添加了名称打印。