【问题标题】:Python - How do I keep a Gtk.Application running when there are no windows?Python - 没有窗口时如何保持 Gtk.Application 运行?
【发布时间】:2021-09-12 21:34:11
【问题描述】:

我想让应用程序在后台运行,即使它的所有窗口都已关闭。有什么功能或东西可以做到这一点吗?我在 SO 上找不到答案。这是我的代码:

import gi
import sys

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

class App(Gtk.Application):
    """The application manager."""

    def __init__(self, *args, **kwargs):
        Gtk.Application.__init__(
            self,
            *args,
            application_id="org.app_test",
            # flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE,
            **kwargs
        )

        # We are only allowed to have one window
        self.window = None

    def do_activate(self):
        """Activate the app."""

        # Create the window, if it does not exist
        if self.window is None:
            self.window = AppWindow(application=self, title="MusicApp", name="0")
            self.window.present()

    def do_startup(self):
        """Start the app."""
        Gtk.Application.do_startup(self)

class AppWindow(Gtk.ApplicationWindow):
    """The main window for the application."""

    def __init__(self, *args, application, **kwargs):
        Gtk.ApplicationWindow.__init__(
            self,
            *args,
            application=application,
            **kwargs
        )

        # The application
        self.app = application

        self.show_all()

if __name__ == "__main__":
    app = App()
    app.run(sys.argv)

当我关闭窗口时,程序停止。即使所有窗口都关闭了,如何让它继续运行?

【问题讨论】:

    标签: python window gtk


    【解决方案1】:

    您可以使用my_app.hold() 让应用程序认为有一个额外的窗口打开,然后在窗口关闭时不会关闭应用程序,因为它认为有另一个不存在的窗口打开。

    PyGObject API Reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      相关资源
      最近更新 更多