在PyQt5中创建桌面应用程序的可移植版本

时间:2018-04-13 09:07:30

标签: python qt pyqt anaconda desktop-application

我在QtCreator 5中创建了一个UI。然后,我将UI文件“Odor.ui”转换为“ui-main.py”。然后我使用Anaconda框架在Upiter Notebook中编写计算部分。什么时候,我编译这段代码

import os
import sys
import pandas as pd
import numpy
import scipy.stats
import xlsxwriter
import re
from PyQt5.QtWidgets import QApplication, QMainWindow, qApp, QWidget, QInputDialog, QLineEdit, QFileDialog, QMessageBox, QTableWidgetItem, QHeaderView
from PyQt5.QtCore import Qt, QEvent, QObject
from PyQt5.QtCore import pyqtSlot
from PyQt5 import QtGui
from ui_main import Ui_MainWindow
from os import walk
from os.path import expanduser as ospath
import glob
from time import gmtime, strftime




class MyMainWindow(QMainWindow, Ui_MainWindow):


def __init__(self, parent=None):
    super(MyMainWindow, self).__init__(parent)
    qApp.installEventFilter(self)
    self.setupUi(self)
    self.dataChooseBtn.clicked.connect(self.selectFile)

    self.saveSample_btn.clicked.connect(self.saveSample)

    self.data_processing.clicked.connect(self.process)

    self.string_processing.clicked.connect(self.processString)

    self.saveSampleString.clicked.connect(self.saveSampleStr)

    self.refreshSample()
    self.refreshSamples.clicked.connect(self.refreshSample)

    self.refreshSample_2()
    self.refreshSamples_2.clicked.connect(self.refreshSample_2)

    self.show()



def eventFilter(self, obj, event):
    if event.type() == QEvent.KeyPress:
        if event.key() == Qt.Key_Escape:
            self.close()
    return super(MyMainWindow, self).eventFilter(obj, event)


@pyqtSlot()
def accept(self):
    textboxValue = self.paramInput_field_2.text()
    QMessageBox.information(self, 'Message', "Значения параметрического столбца: " + textboxValue, QMessageBox.Ok, QMessageBox.Ok)



def selectFile(self):
    self.fileName = None
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    fileName, _ = QFileDialog.getOpenFileName(self,"Выберите стандартизированную выборку", "./Unprocessed samples","All Files (*);;Python Files (*.py)", options=options)
    if fileName:
        self.fileName = fileName






def process(self):

    sample_param = pd.read_excel(self.fileName, header = None, sheetname = 1)
    param = sample_param[0].tolist()


    sample = pd.read_excel(self.fileName, sheetname = 0)

    list_of_index = []
    for i in range(len(sample.columns)):
        sample2 = sample.iloc[:, lambda sample: [i]]
        sample2 = sample2.columns[0]
        list_of_index.append(sample2)
    list_of_index   

    fulllist = []
    for i in list_of_index:
        sample3 = sample[i].tolist()
        fulllist.append(sample3)

    fulllist_percent = []
    column_percent = []
    len(fulllist)
    for i in range(len(fulllist)):
        for j in range(len(fulllist[i])):
            percent_rank = scipy.stats.percentileofscore(fulllist[i], fulllist[i][j])
            column_percent.append(percent_rank)
        fulllist_percent.append(column_percent)
        column_percent = []

    fulllist_rank = []
    for i in range(len(fulllist)):
        rank = len(fulllist[i]) - scipy.stats.rankdata(fulllist[i]) + 1
        fulllist_rank.append(rank)







    param_rank = scipy.stats.rankdata(param).astype(int)

    column_corr = []
    for i in range(len(fulllist)):
        correlation = scipy.stats.spearmanr(param_rank[::-1], fulllist_rank[i])
        column_corr.append(correlation[0])

    fulllist_click = []
    for j in range (len(fulllist_percent)):
        middle = []
        if column_corr[j] > 0:
            for i in range(len(fulllist_percent[j])):
                solve = column_corr[j] * fulllist_percent[j][i]
                middle.append(solve)
        else:
            for i in range (len(fulllist_percent[j])):    
                solve = abs(column_corr[j]) * (100 - fulllist_percent[j][i])
                middle.append(solve)
        fulllist_click.append(middle)

    list_of_rowsumm = []
    rowsumm = 0
    fulllist_clickT = numpy.asarray(fulllist_click).T.tolist()

    for i in range(len(fulllist_clickT)):
        rowsumm = sum(fulllist_clickT[i])
        list_of_rowsumm.append(rowsumm)

    percent_rowsumm = []
    for i in list_of_rowsumm:
        x = scipy.stats.percentileofscore(list_of_rowsumm, i)
        percent_rowsumm.append(x)  

    validity = scipy.stats.pearsonr(list_of_rowsumm, param)
    validity = validity[0]

    additional_info = []
    additional_info.append(list_of_rowsumm)
    additional_info.append(percent_rowsumm)
    additional_info.append(param)



    self.fulllist = fulllist
    self.fulllist_percent = fulllist_percent
    self.fulllist_click = fulllist_click
    self.additional_info = additional_info
    self.validity = validity


    return self.fulllist, self.fulllist_percent, self.fulllist_click, self.additional_info, self.validity



def saveSample(self):


    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    fileNameSave, _ = QFileDialog.getSaveFileName(self,"Сохранить данные выборки","./Samples","Excel files (*.xlsx)", options=options)

    workbook = xlsxwriter.Workbook(fileNameSave + ' ['+ str(round(self.validity, 3)) + ', ' + str(len(self.fulllist)) + ', ' + str(len(self.fulllist[0])) + ']' + ".xlsx")
    worksheet1 = workbook.add_worksheet()
    worksheet2 = workbook.add_worksheet()
    worksheet3 = workbook.add_worksheet()
    worksheet4 = workbook.add_worksheet()

    row = 0

    for col, data in enumerate(self.fulllist):
        worksheet1.write_column(row, col, data)
    for col, data in enumerate(self.fulllist_percent):
        worksheet2.write_column(row, col, data)   
    for col, data in enumerate(self.fulllist_click):
        worksheet3.write_column(row, col, data) 
    for col, data in enumerate(self.additional_info):
        worksheet4.write_column(row, col, data)

    workbook.close()

def processString(self):

    check = self.stringInput_field.toPlainText()
    check = [float(i) for i in check.replace(',', '.').split()]


    index = self.sampleChoose_list.selectedIndexes()[0].row()
    sample_path = self.sample_directory[1][index]

    sample_param = pd.read_excel(ospath(sample_path), header = None, sheetname = 3)
    param = sample_param[2].tolist()
    param_rank = scipy.stats.rankdata(param).astype(int)


    sample_2 = pd.read_excel(ospath(sample_path), header = None, sheetname = 0)

    fulllist_new = []
    for i in range(len(sample_2.columns)):
        column_new = sample_2[i].tolist()
        fulllist_new.append(column_new)
    for i in range(len(check)):
        fulllist_new[i][0] = check[i]


    fulllist_percent_new = []
    column_percent_new = []
    for i in range(len(fulllist_new)):
        for j in range(len(fulllist_new[i])):
            percent_rank = scipy.stats.percentileofscore(fulllist_new[i], fulllist_new[i][j])
            column_percent_new.append(percent_rank)
        fulllist_percent_new.append(column_percent_new)
        column_percent_new = []






    fulllist_rank_new = []
    for i in range(len(fulllist_new)):
        rank = len(fulllist_new[i]) - scipy.stats.rankdata(fulllist_new[i]) + 1
        fulllist_rank_new.append(rank)

    column_corr_new = []
    for i in range(len(fulllist_new)):
        correlation = scipy.stats.spearmanr(param_rank[::-1], fulllist_rank_new[i])
        column_corr_new.append(correlation[0])


    fulllist_click_new = []
    for j in range (len(fulllist_percent_new)):
        middle = []
        if column_corr_new[j] > 0:
            for i in range(len(fulllist_percent_new[j])):
                solve = column_corr_new[j] * fulllist_percent_new[j][i]
                middle.append(solve)
        else:
            for i in range (len(fulllist_percent_new[j])):    
                solve = abs(column_corr_new[j]) * (100 - fulllist_percent_new[j][i])
                middle.append(solve)
        fulllist_click_new.append(middle)

    check_click = []
    for i in range(len(check)):
        if column_corr_new[i] > 0:
            click = fulllist_percent_new[i][0] * column_corr_new[i]
            check_click.append(click) 
        elif column_corr_new[i] < 0:
            click = abs(column_corr_new[i]) * (100 - fulllist_percent_new[i][0])
            check_click.append(click) 
    len(check_click)

    list_of_rowsumm_new = []
    rowsumm = 0
    fulllist_click_newT = numpy.asarray(fulllist_click_new).T.tolist()
    for i in range(len(fulllist_click_newT)):
        rowsumm = sum(fulllist_click_newT[i])
        list_of_rowsumm_new.append(rowsumm)

    percent_rowsumm_new = []
    for i in list_of_rowsumm_new:
        x = scipy.stats.percentileofscore(list_of_rowsumm_new, i)
        percent_rowsumm_new.append(x)


    validity_new = scipy.stats.pearsonr(list_of_rowsumm_new[1:], param[1:])
    validity_new = validity_new[0]
    validity_list = []
    validity_list.append(validity_new)



    additional_info_new = []
    additional_info_new.append(list_of_rowsumm_new)
    additional_info_new.append(percent_rowsumm_new)
    additional_info_new.append(validity_list)
    additional_info_new.append(param)



    self.fulllist_new = fulllist_new
    self.fulllist_percent_new = fulllist_percent_new
    self.fulllist_click_new = fulllist_click_new
    self.additional_info_new = additional_info_new
    self.validity_new = validity_new


    return self.fulllist_new, self.fulllist_percent_new, self.fulllist_click_new, self.additional_info_new, self.validity_new

def saveSampleStr(self):

    time = strftime("%d:%m:%Y %H-%M", gmtime())
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    fileNameSave, _ = QFileDialog.getSaveFileName(self,"Сохранить обработанную строку","./Processed","Excel files (*.xlsx)", options=options)


    workbook = xlsxwriter.Workbook(fileNameSave + ' (' + time + ')' + ".xlsx")
    worksheet1 = workbook.add_worksheet()
    worksheet2 = workbook.add_worksheet()
    worksheet3 = workbook.add_worksheet()
    worksheet4 = workbook.add_worksheet()

    row = 0

    for col, data in enumerate(self.fulllist_new):
        worksheet1.write_column(row, col, data)
    for col, data in enumerate(self.fulllist_percent_new):
        worksheet2.write_column(row, col, data)   
    for col, data in enumerate(self.fulllist_click_new):
        worksheet3.write_column(row, col, data) 
    for col, data in enumerate(self.additional_info_new):
        worksheet4.write_column(row, col, data)

    workbook.close()

def refreshSample(self): 
    sample_directory = []
    sample_files = []
    for (dirpath, dirnames, filenames) in walk('./Samples'):
        filenames = [f for f in filenames if not f[0] == '.']
        sample_files.extend(filenames)
        break
    the_dir = "Samples"
    paths = [os.path.abspath(os.path.join(the_dir,filename)) for filename in os.listdir(the_dir) if not filename.startswith('.')]    

    sample_directory.append(sample_files)
    sample_directory.append(paths)
    self.sample_directory = sample_directory

    self.sampleChoose_list.clear()
    self.sampleChoose_list.addItems(sample_directory[0])
    self.sampleChoose_list.setSortingEnabled(True);
    self.sampleChoose_list.sortItems()

    return self.sample_directory

def refreshSample_2(self): 
    sample_directory_2 = []
    sample_files_2 = []
    for (dirpath, dirnames, filenames) in walk('./Processed'):
        filenames = [f for f in filenames if not f[0] == '.']
        sample_files_2.extend(filenames)
        break
    the_dir = "Processed"
    paths_2 = [os.path.abspath(os.path.join(the_dir,filename)) for filename in os.listdir(the_dir) if not filename.startswith('.')]    

    sample_directory_2.append(sample_files_2)
    sample_directory_2.append(paths_2)

    processed_info = []
    for i in range(len(sample_directory_2[0])):
        file_info = []
        sample_file_2 = sample_directory_2[0][i]
        sample_path_2 = sample_directory_2[1][i]            
        sample_info_2 = pd.read_excel(ospath(sample_path_2), header = None, sheetname = 3)
        sample_info_2 = sample_info_2.iloc[0][0:3]
        file_info.append(sample_file_2)
        sample_info_2_list = numpy.array(sample_info_2).tolist() 
        file_info.extend(sample_info_2_list)
        processed_info.append(file_info)

    self.clickSample_list.setRowCount(len(processed_info))
    self.clickSample_list.setColumnCount(4)

    labels = ['Имя', 'Массовые отклики', 'Процентранг, %', 'Валидность']
    self.clickSample_list.setHorizontalHeaderLabels(labels)

    red = QtGui.QColor(255, 5, 5);
    orange = QtGui.QColor(255, 157, 0);
    blue = QtGui.QColor(0, 46, 255);


    for row in range(len(processed_info)):
        for column in range(len(processed_info[row])):
            self.clickSample_list.setItem(row, column, QTableWidgetItem(str(processed_info[row][column])))
            if column == 2:
                if processed_info[row][column] > 85:
                    color = red;
                if processed_info[row][column] > 65 and processed_info[row][column] < 85:
                    color = orange;
                if processed_info[row][column] < 65:
                    color = blue;
                self.clickSample_list.item(row, column).setBackground(color);    
    self.clickSample_list.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)


if __name__ == '__main__':
app = QApplication(sys.argv)
win = MyMainWindow()
sys.exit(app.exec_())

我的应用是在一个窗口中启动的,而用户界面是由from ui_main import Ui_MainWindow加载的。enter image description here我的问题是,如何制作桌面应用?我是否需要在特殊的Qt5创建者文件中执行此操作?或者可以从Anaconda的.ipynb文件中删除它?我正在尝试制作MacO和Windows版本,但我对应用程序构建和编程很新,并且不知道如何开始。

1 个答案:

答案 0 :(得分:0)

您可以使用cx_Freeze从python程序创建桌面应用程序。

guide to packaging a PyQt application

cxfreeze-quickstart # generates a creation script

在OSX上,您可以通过在提示符下执行以下操作之一来构建.dmg或.app:

python setup.py bdist_dmg
python setup.py bdist_mac

在Windows上:

python setup.py bdist_msi

对部署工具here进行了比较。