将主窗口代码替换class MyWindow(QMainWindow):
from PyQt5.QtWidgets import QApplication, QMessageBox, QMainWindow from PyQt5.QtCore import QSharedMemory, QProcess import sys import os import pygetwindow as gw class SingleApplication(QApplication): def __init__(self, argv=[]): super(SingleApplication, self).__init__(argv) self.window = None self.mem = QSharedMemory("YourAppUniqueString") # 应用程序唯一字符串 self.is_running = self.mem.attach() if self.is_running: self.mem.detach() def check_is_running(self): if self.is_running: # 获取已经运行的窗口句柄 hwnd = gw.getWindowsWithTitle(app_title)[0]._hWnd # 恢复窗口 gw.Window(hwnd).restore() # 激活窗口 gw.Window(hwnd).activate() # 关闭此次程序 os.system("taskkill /F /PID %s" % os.getpid()) return True return False def run(self, window): if not self.is_running: self.mem.create(1) self.window = window self.window.show() class MyWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle(app_title) if __name__ == "__main__": app_title = 'My Window' app = SingleApplication(sys.argv) if not app.check_is_running(): window = MyWindow() # 你的主窗口类 app.run(window) sys.exit(app.exec_())