如何使我的PyQt5应用一个实例? [英] How can I make my PyQt5 app oney one instance?

查看:75
本文介绍了如何使我的PyQt5应用一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现的目标:

  • 当我从开始菜单运行应用程序时,应用程序启动(如果应用程序未运行).
  • 如果某个应用已在运行,则不要创建其他实例,只需显示先前运行的应用窗口即可.

我尝试过的事情:

  • 在目录中创建了一个 .txt文件,并写入" running "&在打开&时将"未运行"插入文件退出窗口.并从一开始就检查文件内容.例如:启动应用程序时:1.)检查文件内容,2.)如果文件内容为"正在运行",请显示警告&退出应用程序.3)如果文件内容为"未运行",则将"正在运行"写入文件&中.启动应用程序4.)在退出时将"未运行"写入文件.
  • created a .txt file in a directory, write 'running' & 'not running' into the file while opening & exiting the window. And checking the file contents at very start. For ex: When starting app: 1.) Check the file content, 2.) If file content is 'running', show warning & exit the app 3.) If file content is 'not running', write 'running' into the file & start app 4.) Write 'not running' into the file on exit.

我面临的问题:

  • 此方法似乎不适合实现此目的.

  • This method doesn't feel like the right way to achieve this.

如果文件项显示"未运行",则应用显示警告并退出.当我希望它显示已经运行的实例时.

If file item says 'not running', app shows warning and exits. While I want it to show already running instance.

由于代码中的某些错误而退出应用程序时,文件项未更新为"未运行"(因为该部分由于错误而无法访问)

File items not updated to 'not running' when app exits because of some error in code (because that part is never reached due to error)

有人可以帮我吗?

推荐答案

您可以使用win32gui模块实现类似的功能.要安装它,请键入CMD pip install pywin32 .现在这是代码:

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链接

Stack Overflow获取列表每个打开的窗口的数量

这篇关于如何使我的PyQt5应用一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆