How to dismiss the Kivy pop-up via a Button?

徘徊边缘 提交于 2020-02-08 07:14:06

问题


I have a pop-up created with Kivy, which contains 2 buttons. User can dismiss the pop-up by pressing outside of the pop-up area (auto_dismiss = True), or by clicking the "No" button. Selecting the "Yes" button, will exit the whole application.

Please see relevant code:

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

The problem now lays with pressing the "No" button. When that is pressed, the code exits with this error:

 on_press = self.popup_exit.dismiss,

AttributeError: 'Button' object has no attribute 'popup_exit'

Any idea how I can fix this as easily as possible?


回答1:


You can solve this issue by a lazy function

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

This way, the lookup will occur only when the button is pressed and popup_exit is already in place...




回答2:


Change on_press = self.popup_exit.dismiss to on_press = lambda: self.popup_exit.dismiss() because dismiss is a function and needs to be called when the button is pressed.

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



回答3:


Try this: on_press = self.popup.dismiss() in replacement of on_press = self.popup_exit.dismiss



来源:https://stackoverflow.com/questions/41577205/how-to-dismiss-the-kivy-pop-up-via-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!