Kivy:从另一个弹出窗口中消除一个弹出窗口 [英] Kivy: Dismiss One Popup From Another Popup
问题描述
我使用kivy.factory.Factory
打开弹出窗口,但是当我想关闭它们时,它不起作用.
I use kivy.factory.Factory
to open the popups, but it's not working when I want to close them.
代码:
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类的新对象,因此在您的情况下,屏幕的F.FirstPopup().open()
是与F.FirstPopup().dismiss()
SecondPopup不同,换句话说,您要关闭刚创建的弹出窗口而不是开始窗口.为了使其清晰可见,您可以将代码更改为:
The problem is that every time you call F.Foo()
you are creating a new object of the Foo class, so in your case F.FirstPopup().open()
of the Screen is different from F.FirstPopup().dismiss()
SecondPopup, in other words you are closing a popup that you have just created instead of the start. To make it obvious, you can change your code to:
# ...
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,表示它是一个新对象.
And as you see each time you press it you get a new id indicating that it is a new object.
因此可能的解决方案是保存对由属性创建的对象的引用:
So a possible solution is to save a reference of the object created by a property:
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()
这篇关于Kivy:从另一个弹出窗口中消除一个弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!