如何在kivy应用程序的出口运行方法

2024-04-25 08:14:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在用户试图退出应用程序时运行一个方法,类似于“你确定要退出吗”或“你想保存文件吗”之类的消息,每当用户试图通过单击窗口顶部的“退出”按钮退出时

像这样的东西 on_quit: app.root.saveSession()


Tags: 文件方法用户app应用程序消息onroot
1条回答
网友
1楼 · 发布于 2024-04-25 08:14:30

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

如果您想创建一个优雅的GUI关闭,例如使用socket关闭事件或弹出窗口询问用户是否真的希望这样做,那么为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()

pythonic64提供,他在issue的方式中创建了一个gist主题。在

相关问题 更多 >