猕猴桃-绑定弹出菜单可从另一个窗口小部件实例运行

时间:2018-06-20 23:28:32

标签: popup kivy

我想将关闭弹出窗口(或按下该弹出窗口小部件中的按钮)绑定到打开该弹出窗口的窗口小部件中的功能。

更具体地说,

#:kivy 1.10.0
#:import Factory kivy.factory.Factory

<MainBox>:

    SelectButton:
        id: selectbutton
        text: 'Select'
        on_press: Factory.SelectPopup().open()

    Button:
       text: 'Ask'
       background_color: (0,1,0,1) if selectbutton.selected else (1,0,0,1)

<SelectPopup>:
    title: 'Select from List'
    auto_dismiss: False
    on_dismiss: Factory.SelectButton().set_selection()
    BoxLayout:
        Label:
            text: 'hello'
        Button:
            text: 'ok'
            #on_press: Factory.SelectButton().set_selection()
            on_press: root.dismiss()

和.py文件中

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty
from kivy.uix.popup import Popup

class SelectButton(Button):
    selected = BooleanProperty(False)

    def set_selection(self):
        self.selected = True

class SelectPopup(Popup):
    pass        

class MainBox(BoxLayout):
    pass

class SelectButtonApp(App):
    def build(self):
        return MainBox()

if __name__ == "__main__":
    SelectButtonApp().run()

也就是说,当我取消通过按下selected打开的弹出窗口时,我想将属性SelectButtonTrue设置为SelectButton。我猜尝试的方法行不通,因为on_dismiss调用未引用SelectButton中的MainBox实例。我也尝试过使用ids,但似乎无法轻易在MainBoxSelectPopup等无关的小部件之间传递它们。任何帮助将非常感激。

1 个答案:

答案 0 :(得分:1)

使用app.root.ids访问项目。有两种解决方案。

解决方案1-直接访问,即不要调用set_selection()函数

直接引用selected,即没有 set_selection()函数。

Button:
    text: 'ok'
    on_press:
        app.root.ids.selectbutton.selected = True
        root.dismiss()

解决方案2-调用set_selection()函数

调用set_selection()函数。

Button:
    text: 'ok'
    on_press:
        app.root.ids.selectbutton.set_selection()
        root.dismiss()

输出

Img01 - selected changed to True after popup dismissed