本篇文章承接http://www.cnblogs.com/zhang-zhi/p/7646923.html#3807385,上篇文章描述了对文本文件的简单处理,本章节结合PYQT4实现该功能的GUI图形界面化,简单的UI界面可以更好的提高工具的实用性,所以在此进行一下记录。

主要实现功能效果展示如下:
1、打开本地对话框,选择文件
 【Python】Python PYQT4 GUI编程与exe打包-LMLPHP
2、文件打开,报文输入及报文清空功能
【Python】Python PYQT4 GUI编程与exe打包-LMLPHP
3、核心功能,报文格式转换
【Python】Python PYQT4 GUI编程与exe打包-LMLPHP
4、退出
【Python】Python PYQT4 GUI编程与exe打包-LMLPHP
一、Python GUI开发之PYQT4
1、先安装PYQT4
    有两种方式可以下载:
①pip下载,终端运行pip install pyqt4
【Python】Python PYQT4 GUI编程与exe打包-LMLPHP

②pycharm工具安装
打开pycharm工具,点击“File”→“settings”→“Project:Project Interpreter”→“+(install)”→“输入pyqt4”,安装即可。
【Python】Python PYQT4 GUI编程与exe打包-LMLPHP

2、在pyqt4的安装目录:C:\Users\zg\AppData\Local\Programs\Python\Python36\Lib\site-packages\PyQt4下,找到【Python】Python PYQT4 GUI编程与exe打包-LMLPHP应用程序启动即可。
3、启动designer.exe程序后,进入Qt设计师主界面,就可以开始你的GUI设计之路了。。
【Python】Python PYQT4 GUI编程与exe打包-LMLPHP

4、选择“Main window”窗体,创建~

【Python】Python PYQT4 GUI编程与exe打包-LMLPHP

5、接下来是重点,pyqt4提供了直接将ui文件转为py文件的功能,非常实用,具体方法为:
编辑好ui界面后,点击保存(最好保存在C:\Users\zg\AppData\Local\Programs\Python\Python36\Scripts目录下),终端执行命令:pyuic4 xxx.ui -o xxx.py即可生成py代码文件xxx.py。
6、根据生成的py代码文件,再进行进一步的功能实现,下面贴出我的GUI界面及代码,仅供参考学习~
一个简单的文本处理工具,实现接口报文的转换与生成

【Python】Python PYQT4 GUI编程与exe打包-LMLPHP

代码如下:

 # -*- coding: utf-8 -*-

 # Form implementation generated from reading ui file 'DataRaw.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
import sys
import re
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setupUi(self) def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(850, 740)
# MainWindow.setMaximumSize(850, 740)
#禁止窗口最大化
MainWindow.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)
#禁止拖拉窗口
MainWindow.setFixedSize(MainWindow.width(), MainWindow.height());
MainWindow.setMouseTracking(False)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8(r"C:\Users\zg\Desktop\ico\Facebook.ico")), QtGui.QIcon.Normal,QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(370, 60, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(370, 110, 75, 23))
self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
self.groupBox = QtGui.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(20, 30, 341, 641))
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.textEdit_2 = QtGui.QTextEdit(self.groupBox)
self.textEdit_2.setGeometry(QtCore.QRect(20, 30, 301, 551))
#设置报文框字体
font = QtGui.QFont()
font.setFamily(_fromUtf8("新宋体"))
font.setPointSize(10)
font.setBold(False)
font.setWeight(50)
self.textEdit_2.setFont(font)
self.textEdit_2.setMidLineWidth(1)
#设置报文框垂直滚动条
self.textEdit_2.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
#设置报文框水平滚动条
self.textEdit_2.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
self.textEdit_2.setTabChangesFocus(True)
self.textEdit_2.setUndoRedoEnabled(False)
#设置报文框取消自动换行
self.textEdit_2.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.textEdit_2.setOverwriteMode(False)
self.textEdit_2.setCursorWidth(1)
self.textEdit_2.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByKeyboard | QtCore.Qt.LinksAccessibleByMouse | QtCore.Qt.TextBrowserInteraction | QtCore.Qt.TextEditable | QtCore.Qt.TextEditorInteraction | QtCore.Qt.TextSelectableByKeyboard | QtCore.Qt.TextSelectableByMouse)
self.textEdit_2.setMouseTracking(True)
self.textEdit_2.setAutoFillBackground(False)
self.textEdit_2.setObjectName(_fromUtf8("textEdit_2")) self.pushButton_3 = QtGui.QPushButton(self.groupBox)
self.pushButton_3.setGeometry(QtCore.QRect(20, 590, 101, 41))
self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
self.pushButton_4 = QtGui.QPushButton(self.groupBox)
self.pushButton_4.setGeometry(QtCore.QRect(220, 590, 101, 41))
self.pushButton_4.setObjectName(_fromUtf8("pushButton_4"))
self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)
self.groupBox_2.setGeometry(QtCore.QRect(460, 30, 370, 641))
self.groupBox_2.setObjectName(_fromUtf8("groupBox_2"))
self.textEdit = QtGui.QTextEdit(self.groupBox_2)
self.textEdit.setGeometry(QtCore.QRect(20, 30, 332, 591))
#结果框字体设置
font = QtGui.QFont()
font.setFamily(_fromUtf8("新宋体"))
font.setPointSize(10)
font.setBold(False)
font.setWeight(50)
self.textEdit.setFont(font)
self.textEdit.setMidLineWidth(1)
#结果框垂直滚动条设置开关
self.textEdit.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
# 结果框水平滚动条设置开关
self.textEdit.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
self.textEdit.setTabChangesFocus(True)
self.textEdit.setUndoRedoEnabled(False)
#结果框取消自动换行
self.textEdit.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.textEdit.setOverwriteMode(False)
self.textEdit.setCursorWidth(1)
self.textEdit.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByKeyboard | QtCore.Qt.LinksAccessibleByMouse | QtCore.Qt.TextBrowserInteraction | QtCore.Qt.TextEditable | QtCore.Qt.TextEditorInteraction | QtCore.Qt.TextSelectableByKeyboard | QtCore.Qt.TextSelectableByMouse)
self.textEdit.setMouseTracking(True)
self.textEdit.setAutoFillBackground(False)
self.textEdit.setObjectName(_fromUtf8("textEdit")) # self.customContextMenuRequested(QPoint)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
self.menubar.setObjectName(_fromUtf8("menubar"))
self.menu = QtGui.QMenu(self.menubar)
self.menu.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
self.menu.setObjectName(_fromUtf8("menu"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.action = QtGui.QAction(MainWindow)
self.action.setCheckable(False)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8(r"C:\Users\zg\Desktop\---\ico\Open.ico")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.action.setIcon(icon)
self.action.setShortcutContext(QtCore.Qt.WidgetShortcut)
self.action.setObjectName(_fromUtf8("action"))
self.action_2 = QtGui.QAction(MainWindow)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8(r"C:\Users\zg\Desktop\---\ico\Log Out.ico")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.action_2.setIcon(icon1)
self.action_2.setObjectName(_fromUtf8("action_2"))
self.menu.addAction(self.action)
self.menu.addAction(self.action_2)
self.menubar.addAction(self.menu.menuAction()) self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.action_2, QtCore.SIGNAL(_fromUtf8("triggered()")), MainWindow.close)
QtCore.QObject.connect(self.action, QtCore.SIGNAL(_fromUtf8("triggered()")), self.openfile)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.soap)
QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8("clicked()")), self.http)
QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8("clicked()")), self.openfile)
QtCore.QObject.connect(self.pushButton_4, QtCore.SIGNAL(_fromUtf8("clicked()")), self.textEdit_2.clear)
QtCore.QMetaObject.connectSlotsByName(MainWindow) def soap(self):
linenum = 1
header = 'soap_request(\n\t"StepName=google", \n\t"ExpectedResponse=AnySoap", \n\t"URL=http://api.google.com/search/beta2", \n\t"SOAPEnvelope= "\n\t"<?xml version=\\"1.0\\" encoding=\\"utf-8\\"?>"\n'
last = '\n\t'+'"Snapshot=t1.inf",\n\t"ResponseParam=result",\n\tLAST );'
src = self.textEdit_2.toPlainText()
lines = src.splitlines()
Message = ''
for line in lines:
#判断该行是否为空行
if len(line.strip())>0:
#找出每行第一个非空字符的位置
num = re.search(r'\S', line).span()[0]
if linenum < len(lines):
#对每行进行拼接
line = "\t"+line[:num] + '"' + line[num:].replace('"',r'\"').rstrip() + '"' + '\n'
linenum += 1
else:
line = "\t"+line[:num] + '"' + line[num:].replace('"',r'\"').rstrip() + '"' + ','
else:
line = '\n'
linenum += 1
Message += line
if len(lines)>0:
try:
Trans_Message = header + Message + last
#输出到界面
self.textEdit.clear()
self.textEdit.append(Trans_Message)
except:
print("输入错误")
else:
print("异常")
# http报文转换
def http(self):
linenum = 1
header = 'web_custom_request(\n\t\"name\",\n\t\"Method=POST\",\n\t\"URL=http://{SERVERIP}:7017/ciitcmp/commserver\",\n\t\"Body=\"\n'
last = '\tLAST );'
src = self.textEdit_2.toPlainText()
lines = src.splitlines()
Message = ''
for line in lines:
# 判断是否是空行
if len(line.strip()) == 0 or line.startswith('#'):
continue
# data = '\r\t\n'
linenum += 1
elif len(line.strip()) > 0 and linenum < len(lines):
num = re.search(r'\S', line).span()[0]
data = '\t' + line[:num] + '"' + line[num:].replace('"', r'\"').rstrip() + '"' + '\n'
linenum += 1
else:
num = re.search(r'\S', line).span()[0]
data = '\t' + line[:num] + '"' + line[num:].replace('"', r'\"').rstrip() + '"' + ',' + '\n'
Message += data
if len(lines)>0:
try:
# #print(myMd5_Digest)
Trans_Message = header + Message + last
#输出到界面
self.textEdit.clear()
self.textEdit.append(Trans_Message)
except:
pass
else:
pass
#打开本地文件夹
def openfile(self):
try:
filename = QtGui.QFileDialog.getOpenFileName(self,"Open file","/")
with open(filename, 'r') as f:
FileData = f.read()
self.textEdit_2.setPlainText(FileData)
except:
print("关闭文件对话框!")
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "文本处理工具V2.0 By:---", None))
MainWindow.setStatusTip(_translate("MainWindow", "文本处理工具", None))
self.pushButton.setStatusTip(_translate("MainWindow", "点击将报文转换为soap请求", None))
self.pushButton.setText(_translate("MainWindow", "SOAP", None))
self.pushButton_2.setStatusTip(_translate("MainWindow", "点击将报文转换为http请求", None))
self.pushButton_2.setText(_translate("MainWindow", "HTTP", None))
self.groupBox.setTitle(_translate("MainWindow", "报文", None))
self.textEdit_2.setStatusTip(_translate("MainWindow", "文本输入框", None))
self.pushButton_3.setStatusTip(_translate("MainWindow", "点击打开本地文件", None))
self.pushButton_3.setText(_translate("MainWindow", "Open", None))
self.pushButton_4.setStatusTip(_translate("MainWindow", "点击清除文本框内容", None))
self.pushButton_4.setText(_translate("MainWindow", "Clear", None))
self.groupBox_2.setTitle(_translate("MainWindow", "结果", None))
self.textEdit.setStatusTip(_translate("MainWindow", "结果输出框", None))
self.menu.setTitle(_translate("MainWindow", "文件", None))
self.action.setText(_translate("MainWindow", "打开", None))
self.action.setStatusTip(_translate("MainWindow", "点击打开本地文件", None))
self.action.setShortcut(_translate("MainWindow", "Ctrl+D", None))
self.action_2.setText(_translate("MainWindow", "退出", None))
self.action_2.setStatusTip(_translate("MainWindow", "点击退出程序", None))
self.action_2.setShortcut(_translate("MainWindow", "Ctrl+C", None))
if __name__ =='__main__':
app = QtGui.QApplication(sys.argv)
Form = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
二、将py文件打包成exe文件
    实现exe文件打包的工具很多,如:pyinstaller、py2exe、cxfreeze等,这里使用cxfreeze进行文件打包,直接使用pip install pyinstaller安装pyinstaller即可。
此时可以为exe文件添加自己想要的ico图标,方法如下:
注意:将ico文件放在py文件相同目录下,并修改xxx.spec文件(与xxx.py文件同一目录下,相同名字的spec文件)
【Python】Python PYQT4 GUI编程与exe打包-LMLPHP

打开终端,执行pyinstaller xxx.spec

【Python】Python PYQT4 GUI编程与exe打包-LMLPHP

生成exe文件~

【Python】Python PYQT4 GUI编程与exe打包-LMLPHP

笔者用cxfreeze进行过exe文件的打包,过程中发生了一下,特此记录一下~
①、安装cxfreeze完毕后,到安装目录C:\Users\zg\AppData\Local\Programs\Python\Python36\Scripts\pyinstaller下,运行命令行窗口,执行命令cxfreeze,若发生以下报错

【Python】Python PYQT4 GUI编程与exe打包-LMLPHP

②、需在该目录下,创建cxfreeze.bat文件,文件内容为

【Python】Python PYQT4 GUI编程与exe打包-LMLPHP

3、执行如下命令打包即可
cxfreeze xxx.py --target-dir=d:\dist\ --icon=d:\xxxx.ico
  以上就是就是Python PYQT4的简单应用了,实现的功能比较简单,后续会在进行相应的功能优化,敬请期待~~~
05-11 17:25