[python]使用PyQt4创建windows应用窗体

281 Views

数据挖掘实训课,作业要求:测试使用分类工具、聚类工具以及创建数据挖掘算法的演示程序。前两个都算好说,最后一个任务居然是设计一个界面演示数据挖掘的部分算法。怀着对python面向对象编程和面向窗体编程极不信任的态度,真的在网上找到了python专用的windows窗体开发组件PyQt4 for Python 2.7 and windows 64bit。

1.安装PtQt4

与想象的不同,PyQt4安装非常方便,只要和python版本以及windows版本一致,安装时会在Python的跟目录下安装,测试:


import sys
from PyQt4 import QtGui

没有报错即安装完成

2.PyQt4的简单调用

PyQt4创建窗体的过程为:创建application对象->创建窗体对象->显示窗体对象->调用完全退出监听服务


import sys
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
widget.resize(250, 150)
widget.setWindowTitle('simple')
widget.show()

sys.exit(app.exec_())

3.使用PyQt4创建演示程序

关于PyQt4各个组件的成员和方法就不记录了,直接上代码,做出来还是挺有意思的


#-*- coding:utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtGui import QMessageBox
import sys
QTextCodec.setCodecForTr(QTextCodec.codecForName("utf8"))


class LayoutDialog(QDialog):
    def __init__(self,parent=None):
        super(LayoutDialog,self).__init__(parent)
        self.setWindowTitle(self.tr("数据挖掘算法演示"))
        self.setGeometry(400, 200, 1200, 600)

        data_label=QLabel(self.tr("选择数据集:"))
        classify_label=QLabel(self.tr("分类器:"))
        normalization_label=QLabel(self.tr("归一化:"))
        parameter_label=QLabel(self.tr("输入参数:"))
        validation_label=QLabel(self.tr("验证比例:"))
        otherLabel=QLabel(self.tr("备注:输入的参数以分号结束,回车换行    例:c=1.0;"))
        otherLabel.setFrameStyle(QFrame.Panel|QFrame.Sunken)

        self.data_comboBox=QComboBox()
        self.data_comboBox.insertItem(0,self.tr("iris"))
        self.data_comboBox.insertItem(1,self.tr("digits"))

        self.classify_comboBox=QComboBox()
        self.classify_comboBox.insertItem(0,self.tr("knn"))
        self.classify_comboBox.insertItem(1,self.tr("tree"))
        self.classify_comboBox.insertItem(2,self.tr("bayes"))
        self.classify_comboBox.insertItem(3,self.tr("logistic"))
        self.classify_comboBox.insertItem(4,self.tr("svm"))

        self.normalization_comboBox=QComboBox()
        self.normalization_comboBox.insertItem(0,self.tr("none"))
        self.normalization_comboBox.insertItem(1,self.tr("standard"))
        self.normalization_comboBox.insertItem(2,self.tr("max_min"))

        self.parameter_text=QTextEdit()
        self.validation_text=QLineEdit()

        labelCol=0
        contentCol=1

        leftLayout=QGridLayout()
        leftLayout.addWidget(data_label,1,labelCol)
        leftLayout.addWidget(self.data_comboBox,1,contentCol)
        leftLayout.addWidget(classify_label,2,labelCol)
        leftLayout.addWidget(self.classify_comboBox,2,contentCol)
        leftLayout.addWidget(normalization_label,3,labelCol)
        leftLayout.addWidget(self.normalization_comboBox,3,contentCol)
        leftLayout.addWidget(parameter_label,4,labelCol)
        leftLayout.addWidget(self.parameter_text,4,contentCol)
        leftLayout.addWidget(validation_label,5,labelCol)
        leftLayout.addWidget(self.validation_text,5,contentCol)
        leftLayout.addWidget(otherLabel,6,labelCol,1,2)
        leftLayout.setColumnStretch(0,1)
        leftLayout.setColumnStretch(1,3)

        result_label=QLabel(self.tr("预测结果:"))
        self.descTextEdit=QTextEdit()

        rightLayout=QVBoxLayout()
        rightLayout.setMargin(10)
        rightLayout.addWidget(result_label)
        rightLayout.addWidget(self.descTextEdit)

        OKPushButton=QPushButton(self.tr("确定"))
        CancelPushButton=QPushButton(self.tr("退出"))
        bottomLayout=QHBoxLayout()
        bottomLayout.addStretch()
        bottomLayout.addWidget(OKPushButton)
        bottomLayout.addWidget(CancelPushButton)

        mainLayout=QGridLayout(self)
        mainLayout.setMargin(15)
        mainLayout.setSpacing(10)
        mainLayout.addLayout(leftLayout,0,0)
        mainLayout.addLayout(rightLayout,0,1,1,40)
        mainLayout.addLayout(bottomLayout,1,0,1,5)
        mainLayout.setSizeConstraint(QLayout.SetFixedSize)

        '''事件'''
        OKPushButton.clicked.connect(self.OKPushButton_OnClick)
        CancelPushButton.clicked.connect(self.CancelPushButton_OnClick)

        '''初始值'''
        self.data_comboBox.setCurrentIndex(0)
        self.classify_comboBox.setCurrentIndex(0)
        self.normalization_comboBox.setCurrentIndex(0)
        self.validation_text.setText('0.2')

    def CancelPushButton_OnClick(self):
        QCoreApplication.instance().quit()

    def OKPushButton_OnClick(self):
        data_name = self.data_comboBox.currentText()
        classify_name = self.classify_comboBox.currentText()
        normalization_name = self.normalization_comboBox.currentText()
        parameter_string = self.parameter_text.toPlainText()
        validation_string = self.validation_text.text()
        y_test,y_pred = self.load_datasets_and_classify(data_name,classify_name,normalization_name,parameter_string,validation_string)

        from sklearn.metrics import classification_report
        self.descTextEdit.setText(classification_report(y_test, y_pred))

    def load_datasets_and_classify(self,data_name,classify_name,normalization_name,parameter_string,validation_string):
        from sklearn import datasets
        from sklearn.model_selection import train_test_split

        rate=0.2
        if validation_string !='':
            try:
                rate=float(validation_string)
            except:
                self.alert_info(u"输入的数值必须是0~1的浮点数")
                return

        if data_name == 'iris':
            origin_data=datasets.load_iris()
        elif data_name == 'digits':
            origin_data=datasets.load_digits()
        else:
            self.alert_info(u"未知数据集")
            return

        data=origin_data.data
        target=origin_data.target
        x_train,x_test,y_train,y_test=train_test_split(data,target,test_size=rate)

        if normalization_name=='standard':
            from sklearn import preprocessing
            scaler = preprocessing.StandardScaler().fit(x_train)
            scaler.transform(x_train)
            scaler.transform(x_test)
        elif normalization_name=='max_min':
            from sklearn import preprocessing
            min_max_scaler = preprocessing.MinMaxScaler()
            x_train = min_max_scaler.fit_transform(x_train)
            x_test = min_max_scaler.fit_transform(x_test)
        elif normalization_name=='none':
            pass
        else:
            self.alert_info(u"未知归一化方式")
            return

        if classify_name=='svm':
            from sklearn.svm import SVC
            clf = SVC()
        elif classify_name=='bayes':
            from sklearn import naive_bayes
            clf = naive_bayes.GaussianNB()
        elif classify_name=='tree':
            from sklearn import tree
            clf = tree.DecisionTreeClassifier()
        elif classify_name=='knn':
            from sklearn import neighbors
            clf = neighbors.KNeighborsClassifier()
        elif classify_name=='logistic':
            from sklearn.linear_model import LogisticRegression
            clf = LogisticRegression()
        else:
            self.alert_info(u"未知分类器")
            return

        clf.fit(x_train,y_train)
        y_pred=clf.predict(x_test)
        return y_test,y_pred

    def alert_info(self,info):
        QMessageBox.information(self,u"警告",info)

if __name__ == '__main__':
    app=QApplication(sys.argv)
    dialog=LayoutDialog()
    dialog.show()
    app.exec_()

演示效果

留下回复

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据