pythonpyqt5instance

How can I make my PyQt5 app only one instance?


What I want to achieve:

What I've tried:

Issues I'm facing:

Can anybody please help me out regarding this?


Solution

  • You can achieve something similar with the win32gui module. To install it type into CMD pip install pywin32. Now this is the code:

    from win32 import win32gui
    import sys
    
    def windowEnumerationHandler(hwnd, top_windows):
        top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
    
    top_windows = []
    win32gui.EnumWindows(windowEnumerationHandler, top_windows)
    for i in top_windows:
        if "Program" in i[1]: #CHANGE PROGRAM TO THE NAME OF YOUR WINDOW
            win32gui.ShowWindow(i[0],5)
            win32gui.SetForegroundWindow(i[0])
            sys.exit()
    
    
    from PyQt5.QtWidgets import QApplication, QWidget
    
    def main():
    
        #YOUR PROGRAM GOES HERE
    
        app = QApplication(sys.argv)
    
        w = QWidget()
        w.setGeometry(500, 500, 500, 500)
        w.setWindowTitle('Simple')
        w.show()
    
        sys.exit(app.exec_())
    
    
    if __name__ == '__main__':
        main()
    

    Basically, at the beginning, the program gets the name of every open window. If the window name is equal to the name of the program, then it brings the program to the front and closes the program. If not, then it opens a new program.

    PyWin32 link

    Stack Overflow get a list of every open window