用python的tkinter做了个带UI的小程序,也打包成EXE了,如何限制只能运行一个?

问题描述:

用python的tkinter做了个带UI的小程序,也打包成EXE了,运行没问题,但是发现双击已经运行后,仍然还可以再次双击再打开一个,如何限制只能运行一个?如果程序已经运行,则激活已经存在的程序窗口?有没有简单可靠的方法,谢谢

可以用一个文件存放改程序pid号,启动时去该文件读取pid号,判断程序是否在执行

def close_window(window):
    """关闭友好提示"""
    if QMessageBox().information(None, "标题", "不能重复开启",
                                 QMessageBox.Ok) == QMessageBox.Ok:
        window.close()
 
 
if __name__ == '__main__':
    cf = configparser.ConfigParser()
    status_path = os.path.join(os.getcwd(), 'config', 'status.conf')
    # 判断是否有开启权限,限制多开
    tool_pid = conf_get(cf, status_path, 'tool_pid', 'pid')
    permission = True
    pids = psutil.pids()
    # tool_pid 不为空
    if bool(tool_pid) is True:
        for pid in pids:
            p = psutil.Process(pid)
            if str(pid) == tool_pid and (p.name() == 'AutoTool.exe' or 'autotool.exe'):
                permission = False
                # 弹框提示
                app = QApplication(sys.argv)
                demo = Demo()
                close_window(demo)
            else:
                continue
 
    if permission:
        # 修改pid
        for pid in pids:
            p = psutil.Process(pid)
            if p.name() == 'AutoTool.exe' or 'autotool.exe':
                conf_set(cf, status_path, 'tool_pid', 'pid', str(pid))
                break
        ……