首页 > 解决方案 > 如何使用单个进程重新启动应用程序?

问题描述

我想重新启动我的应用程序,但我按照教程添加了系统托盘图标。每次重新启动应用程序时,系统托盘都不会消失,我发现应用程序由于某种原因没有真正重新启动。

import sys

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class MainWindow(QMainWindow):
    EXIT_CODE_REBOOT = 122
    def __init__(self):
        super().__init__()
        self.restart_button = QPushButton('restart')
        self.restart_button.clicked.connect(self.onRestart)

        self.setCentralWidget(self.restart_button)

        self.systray = QSystemTrayIcon(self)
        icon = self.style().standardIcon(QStyle.SP_TrashIcon)
        self.systray.setIcon(icon)
        self.systray.show()

    def onRestart(self, checked):
        QApplication.exit(self.EXIT_CODE_REBOOT)

if __name__ == '__main__':
    currentExitCode = MainWindow.EXIT_CODE_REBOOT
    while currentExitCode == MainWindow.EXIT_CODE_REBOOT:
        app = QApplication(sys.argv)
        mainwindow = MainWindow()
        mainwindow.show()
        currentExitCode = app.exec()
        app = None

每次重新启动应用程序,之前的系统托盘总是存在,就像它启动另一个进程一样,我想要唯一的进程而不消耗任何资源。

标签: pythonpyqtpyqt5

解决方案


我尝试了你的代码,它在 Linux 上运行良好,但我也发现了关于在 Windows 上退出后持久图标的类似报告(像这样)。

self.systray.hide() 虽然在退出之前做 a应该足够好,但我认为从 Qt 一侧删除对象(而不是通过 using del)可能会更好:

    def onRestart(self, checked):
        self.systray.deleteLater()
        QApplication.exit(self.EXIT_CODE_REBOOT)

推荐阅读