运行 pyqt(pyside) 程序(exe) 时出现问题

发布于 2025-01-10 07:28:58 字数 6274 浏览 0 评论 0原文

我在使用 pyinstaller 将 pyqt 代码转换为 exe 文件时遇到问题

当我在终端上执行此代码( python test.py 之类的东西)时,代码工作正常。 (GUI 启动并且我的程序可以运行)

但是在我使用 pyinstaller 将此代码转换为 exe 文件后,程序/我的计算机冻结了。 (GUI 未启动并发生错误(分页文件太小,无法完成此操作)

我正在使用以下规范文件制作 exe 文件 文档

当我检查exe文件的进程时,它会随着时间的推移创建多个进程。

这是我的代码的一部分


import numpy as np
from src import database as db
from src import backtest as bt
import sys
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
                            QMetaObject, QObject, QPoint, QRect,
                            QSize, QTime, QUrl, Qt, QPropertyAnimation, QEasingCurve, QEventLoop, QThread)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
                           QFont, QFontDatabase, QGradient, QIcon, QIntValidator,
                           QImage, QKeySequence, QLinearGradient, QPainter,
                           QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QApplication, QFrame, QHBoxLayout, QLabel, QMainWindow, QScrollArea, QTableWidget, QTableWidgetItem,
                               QLineEdit, QPushButton, QSizePolicy, QWidget, QGraphicsDropShadowEffect, QSizeGrip)
from PySide6.QtGui import QPainter
import PySide6.QtCharts as QtCharts

if getattr(sys, 'frozen', False):
    # If the application is run as a bundle, the PyInstaller bootloader
    # extends the sys module by a flag frozen=True and sets the app
    # path into variable _MEIPASS'.
    application_path = sys._MEIPASS
else:
    application_path = os.path.dirname(os.path.abspath(__file__))


class Thread(QThread):
    def run(self):
        QThread.sleep(3)


class MainWindow(QMainWindow):
    def __init__(self, app, parent=None):
        QMainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setMinimumSize(800, 600)

        self.tableWidget = self.ui.tableWidget
        self.tableWidget.setRowCount(5)

        # QSizeGrip(self.ui.size_grip_2)
        LineParamList = [self.ui.LineParam1, self.ui.LineParam2, self.ui.LineParam3,
                         self.ui.LineParam4, self.ui.LineParam5, self.ui.LineParam6,
                         self.ui.LineParam7, self.ui.LineParam8, self.ui.LineParam9,
                         self.ui.LineParam10, self.ui.LineParam11, self.ui.LineParam12,
                         self.ui.LineParam13, self.ui.LineParam14, self.ui.LineParam15,
                         self.ui.LineParam16, self.ui.LineParam17, self.ui.LineParam18]


        for LineParam in LineParamList:
            LineParam.setValidator(
                QIntValidator(0, 100, LineParam))
            LineParam.setText('0')


        self.df = db.make_sheet(application_path) #read dataframe from csv file
        self.config = db.read_config(application_path) #read dataframe from csv file

        self.ui.profit_table_button_2.clicked.connect(
            lambda: self.profit_table_show())
        self.ui.run_button_2.clicked.connect(lambda: self.run())

        self.init_param()

        def moveWindow(e):
            if self.isMaximized() == False:
                if e.buttons() == Qt.LeftButton:
                    self.move(self.pos() + e.globalPos() - self.clickPosition)
                    self.clickPosition = e.globalPos()
                    e.accept()

        self.ui.header_frame_2.mouseMoveEvent = moveWindow

        self.thread = Thread()
        self.thread_init = Thread()

        self.thread.finished.connect(lambda: self.ui.run_button_2)
        self.thread_init.finished.connect(lambda: self.init_param)
        self.thread.finished.connect(lambda: self.ui.LineParam1)


    def init_param(self):
        self.ui.LineParam1.textChanged.connect(
            lambda: self.changeSliderParam(self.ui.LineParam1.text(), self.ui.SliderParam1, 'param1'))


    def changeLineParam(self, value, interface, target='param1'):
        value = int(value)
        interface.setText(str(value))
        self.config['coef'][target] = value/100.

    def changeSliderParam(self, value, interface, target='param1'):
        value = int(value)
        interface.setValue(value)
        self.config['coef'][target] = value/100.

    def run(self):
        if not self.thread.isRunning():
            days, Profit, MarketProfit, accumProfit, accumMarketProfit, alpha, Volatility, CARG, SharpRatio = bt.RunBacktest(
                self.config, self.df.copy())
            self.create_profit_table(
                days, Profit, MarketProfit, alpha, accumProfit, accumMarketProfit)
            self.thread.start()

    def profit_table_show(self):
        self.ui.stackedWidget_2.setCurrentIndex(0)

    def mousePressEvent(self, event):
        self.clickPosition = event.globalPos()

    def create_profit_table(self, days, Profit, MarketProfit, alpha, accumProfit, accumMarketProfit):
        # adding label to the layout
        days = list(days)
        self.tableWidget.setColumnCount(alpha.shape[0])
        # plot window goes on right side, spanning 3 rows
        self.tableWidget.setHorizontalHeaderLabels(days[:alpha.shape[0]])

        for idx in range(alpha.shape[0]):
            p = '{:0.2f}%'.format(Profit[idx]*100)
            mp = '{:0.2f}%'.format(MarketProfit[idx]*100)
            alp = '{:0.2f}%'.format(alpha[idx]*100)
            ap = '{:0.2f}%'.format(accumProfit[idx]*100)
            amp = '{:0.2f}%'.format(accumMarketProfit[idx]*100)
            self.tableWidget.setItem(
                0, idx, QTableWidgetItem(p))
            self.tableWidget.setItem(
                1, idx, QTableWidgetItem(mp))
            self.tableWidget.setItem(
                2, idx, QTableWidgetItem(alp))
            self.tableWidget.setItem(
                3, idx, QTableWidgetItem(ap))
            self.tableWidget.setItem(
                4, idx, QTableWidgetItem(amp))

        self.ui.profit_table_cont.addWidget(self.tableWidget)
        self.ui.frame_22.setStyleSheet(u"background-color: transparent")



if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = MainWindow(app)
    window.show()

    sys.exit(app.exec())

I have the problem with converting pyqt code to exe file using pyinstaller

When I execture this code on terminal ( python test.py somthing like that) , code works fine.
(GUI starts and my program works)

But after I convert this code to exe file using pyinstaller, program / my computer freezes.
(GUI dose not start and error occurs (paging file is too small for this operation to complete)

I'm making exe file using spec file following this documents

When I check the process of exe file, it creates multiple processes as time passed.

This is part of my code


import numpy as np
from src import database as db
from src import backtest as bt
import sys
from PySide6.QtCore import (QCoreApplication, QDate, QDateTime, QLocale,
                            QMetaObject, QObject, QPoint, QRect,
                            QSize, QTime, QUrl, Qt, QPropertyAnimation, QEasingCurve, QEventLoop, QThread)
from PySide6.QtGui import (QBrush, QColor, QConicalGradient, QCursor,
                           QFont, QFontDatabase, QGradient, QIcon, QIntValidator,
                           QImage, QKeySequence, QLinearGradient, QPainter,
                           QPalette, QPixmap, QRadialGradient, QTransform)
from PySide6.QtWidgets import (QApplication, QFrame, QHBoxLayout, QLabel, QMainWindow, QScrollArea, QTableWidget, QTableWidgetItem,
                               QLineEdit, QPushButton, QSizePolicy, QWidget, QGraphicsDropShadowEffect, QSizeGrip)
from PySide6.QtGui import QPainter
import PySide6.QtCharts as QtCharts

if getattr(sys, 'frozen', False):
    # If the application is run as a bundle, the PyInstaller bootloader
    # extends the sys module by a flag frozen=True and sets the app
    # path into variable _MEIPASS'.
    application_path = sys._MEIPASS
else:
    application_path = os.path.dirname(os.path.abspath(__file__))


class Thread(QThread):
    def run(self):
        QThread.sleep(3)


class MainWindow(QMainWindow):
    def __init__(self, app, parent=None):
        QMainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setMinimumSize(800, 600)

        self.tableWidget = self.ui.tableWidget
        self.tableWidget.setRowCount(5)

        # QSizeGrip(self.ui.size_grip_2)
        LineParamList = [self.ui.LineParam1, self.ui.LineParam2, self.ui.LineParam3,
                         self.ui.LineParam4, self.ui.LineParam5, self.ui.LineParam6,
                         self.ui.LineParam7, self.ui.LineParam8, self.ui.LineParam9,
                         self.ui.LineParam10, self.ui.LineParam11, self.ui.LineParam12,
                         self.ui.LineParam13, self.ui.LineParam14, self.ui.LineParam15,
                         self.ui.LineParam16, self.ui.LineParam17, self.ui.LineParam18]


        for LineParam in LineParamList:
            LineParam.setValidator(
                QIntValidator(0, 100, LineParam))
            LineParam.setText('0')


        self.df = db.make_sheet(application_path) #read dataframe from csv file
        self.config = db.read_config(application_path) #read dataframe from csv file

        self.ui.profit_table_button_2.clicked.connect(
            lambda: self.profit_table_show())
        self.ui.run_button_2.clicked.connect(lambda: self.run())

        self.init_param()

        def moveWindow(e):
            if self.isMaximized() == False:
                if e.buttons() == Qt.LeftButton:
                    self.move(self.pos() + e.globalPos() - self.clickPosition)
                    self.clickPosition = e.globalPos()
                    e.accept()

        self.ui.header_frame_2.mouseMoveEvent = moveWindow

        self.thread = Thread()
        self.thread_init = Thread()

        self.thread.finished.connect(lambda: self.ui.run_button_2)
        self.thread_init.finished.connect(lambda: self.init_param)
        self.thread.finished.connect(lambda: self.ui.LineParam1)


    def init_param(self):
        self.ui.LineParam1.textChanged.connect(
            lambda: self.changeSliderParam(self.ui.LineParam1.text(), self.ui.SliderParam1, 'param1'))


    def changeLineParam(self, value, interface, target='param1'):
        value = int(value)
        interface.setText(str(value))
        self.config['coef'][target] = value/100.

    def changeSliderParam(self, value, interface, target='param1'):
        value = int(value)
        interface.setValue(value)
        self.config['coef'][target] = value/100.

    def run(self):
        if not self.thread.isRunning():
            days, Profit, MarketProfit, accumProfit, accumMarketProfit, alpha, Volatility, CARG, SharpRatio = bt.RunBacktest(
                self.config, self.df.copy())
            self.create_profit_table(
                days, Profit, MarketProfit, alpha, accumProfit, accumMarketProfit)
            self.thread.start()

    def profit_table_show(self):
        self.ui.stackedWidget_2.setCurrentIndex(0)

    def mousePressEvent(self, event):
        self.clickPosition = event.globalPos()

    def create_profit_table(self, days, Profit, MarketProfit, alpha, accumProfit, accumMarketProfit):
        # adding label to the layout
        days = list(days)
        self.tableWidget.setColumnCount(alpha.shape[0])
        # plot window goes on right side, spanning 3 rows
        self.tableWidget.setHorizontalHeaderLabels(days[:alpha.shape[0]])

        for idx in range(alpha.shape[0]):
            p = '{:0.2f}%'.format(Profit[idx]*100)
            mp = '{:0.2f}%'.format(MarketProfit[idx]*100)
            alp = '{:0.2f}%'.format(alpha[idx]*100)
            ap = '{:0.2f}%'.format(accumProfit[idx]*100)
            amp = '{:0.2f}%'.format(accumMarketProfit[idx]*100)
            self.tableWidget.setItem(
                0, idx, QTableWidgetItem(p))
            self.tableWidget.setItem(
                1, idx, QTableWidgetItem(mp))
            self.tableWidget.setItem(
                2, idx, QTableWidgetItem(alp))
            self.tableWidget.setItem(
                3, idx, QTableWidgetItem(ap))
            self.tableWidget.setItem(
                4, idx, QTableWidgetItem(amp))

        self.ui.profit_table_cont.addWidget(self.tableWidget)
        self.ui.frame_22.setStyleSheet(u"background-color: transparent")



if __name__ == '__main__':
    app = QApplication(sys.argv)

    window = MainWindow(app)
    window.show()

    sys.exit(app.exec())

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文