如何在 kivy 应用程序退出时运行方法

Top*_*ope 6 python kivy

当用户尝试退出应用程序时,我想运行一个方法,有点像“您确定要退出吗”或“您想保存文件吗”类型的消息,每当用户尝试通过单击退出时窗口顶部的退出按钮

就像是 on_quit: app.root.saveSession()

Tor*_*xed 9

如果您希望您的应用程序在 GUI 关闭后简单地运行,最简单和最小的方法是将任何退出代码放在TestApp().run(). run()创建一个无限循环,它还会清除 kivy 中的任何事件数据,因此它不会挂起。一旦 window/gui 实例死掉,这个无限循环就会中断。因此,之后的任何代码都只会在 GUI 消失后才执行。

如果你想创建一个优雅的 GUI 关闭,例如使用套接字关闭事件或弹出窗口询问用户是否真的想要这样做,那么为 on_request_close 事件创建一个钩子是要走的路:

from kivy.config import Config
Config.set('kivy', 'exit_on_escape', '0')

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.core.window import Window


class ChildApp(App):

    def build(self):
        Window.bind(on_request_close=self.on_request_close)
        return Label(text='Child')

    def on_request_close(self, *args):
        self.textpopup(title='Exit', text='Are you sure?')
        return True

    def textpopup(self, title='', text=''):
        """Open the pop-up with the name.

        :param title: title of the pop-up to open
        :type title: str
        :param text: main text of the pop-up to open
        :type text: str
        :rtype: None
        """
        box = BoxLayout(orientation='vertical')
        box.add_widget(Label(text=text))
        mybutton = Button(text='OK', size_hint=(1, 0.25))
        box.add_widget(mybutton)
        popup = Popup(title=title, content=box, size_hint=(None, None), size=(600, 300))
        mybutton.bind(on_release=self.stop)
        popup.open()


if __name__ == '__main__':
    ChildApp().run()
Run Code Online (Sandbox Code Playgroud)

感谢pythonic64,他以某个问题的方式创建了该主题的要点