0

➤ What I want: I have a window & a label in that window, when app is ran for the first time, label shows default text, but if user tries to launch second space, second space doesn't launch, instead it changes the label in the first instance which was already running

➤ Problem I'm facing: I stopped the second instance from running, with help, successfully, but I couldn't understand how to change the label in first instance.

➤ Minimal Reproducible code:

import sys
from PyQt5.QtWidgets import *
from win32 import win32gui


class Window(QMainWindow):

    def __init__(self) -> None:
        super().__init__()
        self.setWindowTitle('My Program')
        self.resize(400, 400)
        self.set_label()
    
    def set_label(self, text='This is an example'):
        self.lab = QLabel(self)
        self.lab.move(50, 50)
        self.lab.setText(text)


if __name__ == "__main__":
    
    # Check if app is already running & Close the app
    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 i[1] == 'My Program':
            print('App is already running')
            
            # I know below line is wrong [tha's why commented out]
            # Window.set_label('Success')       # How to achieve it
            ## I want the label text to be changed in the already running instance
            
            sys.exit()    # Exit app (second instance)
    
    
    # Starting Application
    app = QApplication(sys.argv)
    win = Window()
    win.show()
    app.exec()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Ecto Ruseff
  • 141
  • 1
  • 9
  • I think you probably need to run a thread in the background that checks to see if a new window opens. If it does, then you change the text. I don't think that you can change it from a seoarate window – The Pilot Dude Jan 15 '21 at 08:48
  • @the-pilot-dude, I was thinking of the same, but won't it affect the efficiency of the program (coz it would be running all the time) – Ecto Ruseff Jan 15 '21 at 11:50
  • It would but not by that much because all you would be doing is running a small while loop – The Pilot Dude Jan 15 '21 at 12:10

0 Answers0