如何通过按钮关闭Kivy弹出窗口?

时间:2017-01-10 19:51:23

标签: python button popup kivy dismiss

我有一个用Kivy创建的弹出窗口,其中包含2个按钮。用户可以通过按弹出区域外部(auto_dismiss = True)或单击“否”按钮来关闭弹出窗口。 选择“是”按钮将退出整个应用程序。

请参阅相关代码:

class ExitApp(App):

def exit_confirmation(self):

    # popup can only have one Widget.  This can be fixed by adding a BoxLayout

    self.box_popup = BoxLayout(orientation = 'horizontal')

    self.box_popup.add_widget(Label(text = "Really exit?"))

    self.box_popup.add_widget(Button(
        text = "Yes",
        on_press = ExitApp.exit,
        size_hint = (0.215, 0.075)))

    self.box_popup.add_widget(Button(
        text = "No",
        on_press = self.popup_exit.dismiss,
        size_hint=(0.215, 0.075)))

    self.popup_exit = Popup(title = "Exit",
        content = self.box_popup,
        size_hint = (0.4, 0.4),
        auto_dismiss = True)

    self.popup_exit.open()

def exit(self):

    App.get_running_app().stop()

问题现在按下“否”按钮。按下该按钮后,代码将退出并显示以下错误:

 on_press = self.popup_exit.dismiss,
     

AttributeError:'Button'对象没有属性'popup_exit'

我知道如何尽可能轻松地解决这个问题吗?

4 个答案:

答案 0 :(得分:1)

您可以通过延迟函数解决此问题

on_press = lambda *args: self.popup_exit.dismiss()

这样,当按下按钮并且 popup_exit 已经到位时,查找将仅 ...

答案 1 :(得分:0)

on_press = self.popup_exit.dismiss更改为on_press = lambda: self.popup_exit.dismiss(),因为dismiss是一个函数,需要在按下按钮时调用。

def exit_confirmation(self):


    # popup can only have one Widget.  This can be fixed by adding a BoxLayout

    self.box_popup = BoxLayout(orientation = 'horizontal')

    self.box_popup.add_widget(Label(text = "Really exit?"))

    self.box_popup.add_widget(Button(
        text = "Yes",
        on_press = ExitApp.exit,
        size_hint = (0.215, 0.075)))

    self.popup_exit = Popup(title = "Exit",
        content = self.box_popup,
        size_hint = (0.4, 0.4),
        auto_dismiss = True)

    self.box_popup.add_widget(Button(
    text = "No",
    on_press = lambda: self.popup_exit.dismiss() ,
    size_hint=(0.215, 0.075)))

    self.popup_exit.open()

答案 2 :(得分:0)

kivy中可以进行这种工作吗?

on_press : root.dismiss()

答案 3 :(得分:-1)

试试这个:on_press = self.popup.dismiss()代替on_press = self.popup_exit.dismiss