使用 pyinstaller 构建 onefile 后 QSettings 不起作用

QSettings doesn't work after building onefile using pyinstaller

我在构建我的脚本的 pyinstaller onefile 版本时遇到问题,我的复选框状态没有被保存,但另一方面,当 pyinstaller 使用文件构建普通 exe 时,复选框状态被保存并且工作正常。

请注意,我正在使用资源(包)>__init__.py 来存储我的图标和 config.ini 并且这些图标在两种情况下都适用于一个文件或正常构建。

项目文件图片

__init__.py contents

from pathlib import Path

resources = Path(__file__).parent

config_ini = resources / "config.ini"

My PyQt5 Gui.

import sys

from PyQt5.QtCore import QSettings

import resources

import PyQt5.QtCore
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *



settings = QSettings(str(resources.config_ini), QSettings.IniFormat)


class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.main_ui()
        self.buttons()
        self.layout()
        self.show()
        settings.sync()


    def main_ui(self):
        self.setWindowTitle("Files Organizer")

    def buttons(self):
        self.checkbox_startup = QCheckBox("Run on start up")

        self.checkbox_startup.setChecked(False)
        self.checkbox_startup.setChecked(settings.value("startup_state", type=bool))

        self.checkbox_startup.toggled.connect(self.startup_settings)

    def layout(self):
        self.horizontalGroupBox_options = QGroupBox("Options", self)
        verticalbox_options = QVBoxLayout()
        verticalbox_options.addWidget(self.checkbox_startup)
        self.horizontalGroupBox_options.setLayout(verticalbox_options)
        self.horizontalGroupBox_options.resize(360, 80)
        self.horizontalGroupBox_options.move(20, 110)

    def startup_settings(self):
        startup_state = self.checkbox_startup.isChecked()
        settings.setValue("startup_state", startup_state)
        print("startup state is ", settings.value("startup_state", type=bool))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    screen = Window()
    screen.show()
    app.exec()

用户 Numerlor

在 Python Discord 处在 Whosebug 之外回答

onefile works by extracting it's contents to a temp directory, that has its path stored in sys._MEIPASS. So you setting the values in resources.config_ini only changes the extracted file, which is removed after you close the program

qt has a bunch of paths under QtCore.QStandardPaths.writableLocation that might be where you want to store config, like QtCore.QStandardPaths.writableLocation(QtCore.QStandardPaths.AppConfigLocation) which returns .../appdata/local/{org}/{app}

这些行是在 GUI 的开头添加的。

# This return .../appdata/local
local_path = QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation) 
# Make directory for my program
os.makedirs(local_path + "\" + "FilesOrganizer", exist_ok=True) 
# Making config.ini file.
config_path = local_path + "\" + "FilesOrganizer" + "\" + "config.ini" 
settings = QSettings(config_path, QSettings.IniFormat)