访问kivy popup父级

时间:2016-10-16 18:37:28

标签: python python-2.7 popup kivy

弹出窗口在kivy中实现的方式,弹出窗口似乎附加到窗口而不是创建弹出窗口的父对象。 Popup附带了self.dismiss()以关闭弹出窗口,但我无法找到任何方法来访问'父'对象,因为尽管创建弹出窗口,它似乎存在于它之外。

示例摘录:

class StartButton(ActionButton)
    def on_release(self):
        self.popup = StartPop(id='popid')
        self.popup.open()

class StartPop(Popup):
    def close(self):
        self.dismiss()
    def start(self):
        print(self)
        print(self.parent)

打印命令的结果是

<__main__.StartPop object at 0x00000000037BBCE0>

<kivy.core.window.window_sdl2.WindowSDL object at 0x000000000373B0B0>

因此,而不是父级是StartButton,我的父级也希望访问它,父级是Window。

我没有看到如何绑定任何与我用来创建弹出窗口的窗口小部件交互的函数。我需要能够让父对象及其父对象根据我在弹出窗口中单击的内容做一些事情,但我无法弄清楚如何实现它。

在.kv文件中

<StartPop>:
    title: 'Popup'
    auto_dismiss: True
    size_hint: None,None
    size: 400,250
    BoxLayout:
        orientation: 'vertical'
        Label:
            text: 'sample text here'
            text_size: self.size
            halign: 'center'
            valign: 'middle'
        BoxLayout:
            orientation: 'horizontal'
            Button:
                size_hint: 1,0.5
                text: 'Cancel'
                on_release: root.close()
            Button:
                size_hint: 1,0.5
                text: 'Start Testing'
                on_release: root.start()

1 个答案:

答案 0 :(得分:2)

它是这样实现的,因为它需要在大多数时间被隐藏,但仍然是活动的,以便可以调用open()。 Kivy似乎没有办法隐藏小部件以实际删除并在某处保留引用(没有hide属性),所以甚至可能因为那个。或者因为以这种方式实现它更容易。然而,它的实现并不差,并且OO编程的工作方式也可以用它做一些奇特的东西。只需使用kwargs中的__init__处理您想要的内容:

从Popup继承并获取自定义关键字参数:

class StartPop(Popup):
    def __init__(self, **kwargs):
        self.caller = kwargs.get('caller')
        super(StartPop, self).__init__(**kwargs)
        print self.caller

然后创建该自定义Popup的实例并设置父级:

pop = StartPop(caller=self)
pop.open()

caller关键字不仅限于Kivy小部件。放置任何您想要处理的对象,然后您可以通过StartPop

self.caller对象中访问它