Skip to main content
 首页 » 编程设计

python之访问 kivy 弹出父级

2024年10月17日10tintown

弹出窗口在 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。

我不知道如何绑定(bind)任何函数,从而与我用来创建弹出窗口的小部件进行交互。我需要能够让父对象及其父对象根据我在弹出窗口中单击的内容来执行操作,但我不知道如何实现。

在.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() 

请您参考如下方法:

它是这样实现的,因为它需要在大部分时间隐藏,但仍处于事件状态,以便可以调用 open()。 Kivy 似乎没有以其他方式处理小部件的隐藏,实际上删除 它并在某处保留引用(没有 hide 属性),所以甚至可能是因为那个。或者因为这样更容易实现。然而,它的实现还不错,而且 OO 编程的工作方式也可以用它做一些奇特的事情。你想要的东西可以简单地用 __init__ 中的 kwargs 来处理:

继承自 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 小部件。将您想要处理的任何对象放在那里,然后您可以通过 self.caller

在 StartPop 对象中访问它