Kivy:从另一个弹出窗口中关闭一个弹出窗口

Kivy: Dismiss One Popup From Another Popup

我用kivy.factory.Factory打开弹出窗口,但当我想关闭它们时它不起作用。

代码:

from kivy.app import App
from kivy.lang import Builder


x = Builder.load_string("""
#:import F kivy.factory.Factory
#:import Window kivy.core.window.Window

Screen:
    Button:
        text: 'Press to Open First Popup'
        on_press:
            F.FirstPopup().open()

<FirstPopup@Popup>:
    title: 'First Popup'
    size_hint: None, None
    width: Window.width / 1.4
    height: Window.width / 1.4

    Button:
        text: 'Press to Open Second Popup'
        on_press: F.SecondPopup().open()

<SecondPopup@Popup>:
    title: 'Second Popup'
    size_hint: None, None
    width: Window.width / 1.8
    height: Window.width / 1.8

    Button:
        text: 'Press to Close Both Popups'
        on_press:
            root.dismiss()
            F.FirstPopup().dismiss() # < DOSEN'T WORK
""")

class MyApp(App):

    def build(self):
        return x

MyApp().run()

问题是每次调用 F.Foo() 时都会创建 Foo class 的新对象,因此在您的情况下 F.FirstPopup().open() 的 Screen 不同于 F.FirstPopup().dismiss() SecondPopup,换句话说,您正在关闭刚刚创建的弹出窗口而不是开始。为使其显而易见,您可以将代码更改为:

# ...
Button:
    text: 'Press to Close Both Popups'
    on_press:
        print(F.FirstPopup())

获得以下内容:

<kivy.factory.FirstPopup object at 0x7f8f9a183e18>
<kivy.factory.FirstPopup object at 0x7f8f996fc118>
<kivy.factory.FirstPopup object at 0x7f8f996fc388>
<kivy.factory.FirstPopup object at 0x7f8f996fc5f8>
<kivy.factory.FirstPopup object at 0x7f8f996fc528>
<kivy.factory.FirstPopup object at 0x7f8f996fc2b8>
<kivy.factory.FirstPopup object at 0x7f8f996fc048>

正如您所看到的,每次按下它都会得到一个新的 ID,表明它是一个新对象。

所以一个可能的解决方案是保存由 属性:

创建的对象的引用
from kivy.app import App
from kivy.lang import Builder

x = Builder.load_string("""
#:import F kivy.factory.Factory
#:import Window kivy.core.window.Window

Screen:
    Button:
        text: 'Press to Open First Popup'
        on_press:
            F.FirstPopup().open()

<FirstPopup@Popup>:
    title: 'First Popup'
    size_hint: None, None
    width: Window.width / 1.4
    height: Window.width / 1.4
    Button:
        text: 'Press to Open Second Popup'
        on_press: 
            second_popup = F.SecondPopup()
            second_popup.first_popup = root
            second_popup.open()

<SecondPopup@Popup>:
    title: 'Second Popup'
    size_hint: None, None
    width: Window.width / 1.8
    height: Window.width / 1.8
    first_popup: None
    Button:
        text: 'Press to Close Both Popups'
        on_press:
            root.dismiss()
            if root.first_popup is not None: root.first_popup.dismiss()
""")

class MyApp(App):
    def build(self):
        return x

MyApp().run()