【Python】Python PYQT4 GUI編程與exe打包

  本篇文章承接http://www.cnblogs.com/zhang-zhi/p/7646923.html#3807385,上篇文章描述了對文本文件的簡單處理,本章節結合PYQT4實現該功能的GUI圖形界面化,簡單的UI界面能夠更好的提升工具的實用性,因此在此進行一下記錄。html

主要實現功能效果展現以下:
一、打開本地對話框,選擇文件
 
二、文件打開,報文輸入及報文清空功能
三、核心功能,報文格式轉換
四、退出
1、Python GUI開發之PYQT4
一、先安裝PYQT4
    有兩種方式能夠下載:
①pip下載,終端運行pip install pyqt4
②pycharm工具安裝
打開pycharm工具,點擊「File」→「settings」→「Project:Project Interpreter」→「+(install)」→「輸入pyqt4」,安裝便可。
二、在pyqt4的安裝目錄:C:\Users\zg\AppData\Local\Programs\Python\Python36\Lib\site-packages\PyQt4下,找到 應用程序啓動便可。
三、啓動designer.exe程序後,進入Qt設計師主界面,就能夠開始你的GUI設計之路了。。

四、選擇「Main window」窗體,建立~web

五、接下來是重點,pyqt4提供了直接將ui文件轉爲py文件的功能,很是實用,具體方法爲:
編輯好ui界面後,點擊保存(最好保存在C:\Users\zg\AppData\Local\Programs\Python\Python36\Scripts目錄下),終端執行命令:pyuic4 xxx.ui -o xxx.py便可生成py代碼文件xxx.py。
六、根據生成的py代碼文件,再進行進一步的功能實現,下面貼出個人GUI界面及代碼,僅供參考學習~
一個簡單的文本處理工具,實現接口報文的轉換與生成

 

代碼以下:api

  1 # -*- coding: utf-8 -*-
  2 
  3 # Form implementation generated from reading ui file 'DataRaw.ui'
  4 #
  5 # Created by: PyQt4 UI code generator 4.11.4
  6 #
  7 # WARNING! All changes made in this file will be lost!
  8 import sys
  9 import re
 10 from PyQt4 import QtCore, QtGui
 11 try:
 12     _fromUtf8 = QtCore.QString.fromUtf8
 13 except AttributeError:
 14     def _fromUtf8(s):
 15         return s
 16 
 17 try:
 18     _encoding = QtGui.QApplication.UnicodeUTF8
 19     def _translate(context, text, disambig):
 20         return QtGui.QApplication.translate(context, text, disambig, _encoding)
 21 except AttributeError:
 22     def _translate(context, text, disambig):
 23         return QtGui.QApplication.translate(context, text, disambig)
 24 
 25 class Ui_MainWindow(QtGui.QMainWindow):
 26     def __init__(self):
 27         QtGui.QMainWindow.__init__(self)
 28         self.setupUi(self)
 29 
 30     def setupUi(self, MainWindow):
 31         MainWindow.setObjectName(_fromUtf8("MainWindow"))
 32         MainWindow.resize(850, 740)
 33         # MainWindow.setMaximumSize(850, 740)
 34         #禁止窗口最大化
 35         MainWindow.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)
 36         #禁止拖拉窗口
 37         MainWindow.setFixedSize(MainWindow.width(), MainWindow.height());
 38         MainWindow.setMouseTracking(False)
 39         icon = QtGui.QIcon()
 40         icon.addPixmap(QtGui.QPixmap(_fromUtf8(r"C:\Users\zg\Desktop\ico\Facebook.ico")), QtGui.QIcon.Normal,QtGui.QIcon.Off)
 41         MainWindow.setWindowIcon(icon)
 42         self.centralwidget = QtGui.QWidget(MainWindow)
 43         self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
 44         self.pushButton = QtGui.QPushButton(self.centralwidget)
 45         self.pushButton.setGeometry(QtCore.QRect(370, 60, 75, 23))
 46         self.pushButton.setObjectName(_fromUtf8("pushButton"))
 47         self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
 48         self.pushButton_2.setGeometry(QtCore.QRect(370, 110, 75, 23))
 49         self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
 50         self.groupBox = QtGui.QGroupBox(self.centralwidget)
 51         self.groupBox.setGeometry(QtCore.QRect(20, 30, 341, 641))
 52         self.groupBox.setObjectName(_fromUtf8("groupBox"))
 53         self.textEdit_2 = QtGui.QTextEdit(self.groupBox)
 54         self.textEdit_2.setGeometry(QtCore.QRect(20, 30, 301, 551))
 55         #設置報文框字體
 56         font = QtGui.QFont()
 57         font.setFamily(_fromUtf8("新宋體"))
 58         font.setPointSize(10)
 59         font.setBold(False)
 60         font.setWeight(50)
 61         self.textEdit_2.setFont(font)
 62         self.textEdit_2.setMidLineWidth(1)
 63         #設置報文框垂直滾動條
 64         self.textEdit_2.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
 65         #設置報文框水平滾動條
 66         self.textEdit_2.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
 67         self.textEdit_2.setTabChangesFocus(True)
 68         self.textEdit_2.setUndoRedoEnabled(False)
 69         #設置報文框取消自動換行
 70         self.textEdit_2.setLineWrapMode(QtGui.QTextEdit.NoWrap)
 71         self.textEdit_2.setOverwriteMode(False)
 72         self.textEdit_2.setCursorWidth(1)
 73         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)
 74         self.textEdit_2.setMouseTracking(True)
 75         self.textEdit_2.setAutoFillBackground(False)
 76         self.textEdit_2.setObjectName(_fromUtf8("textEdit_2"))
 77 
 78         self.pushButton_3 = QtGui.QPushButton(self.groupBox)
 79         self.pushButton_3.setGeometry(QtCore.QRect(20, 590, 101, 41))
 80         self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
 81         self.pushButton_4 = QtGui.QPushButton(self.groupBox)
 82         self.pushButton_4.setGeometry(QtCore.QRect(220, 590, 101, 41))
 83         self.pushButton_4.setObjectName(_fromUtf8("pushButton_4"))
 84         self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)
 85         self.groupBox_2.setGeometry(QtCore.QRect(460, 30, 370, 641))
 86         self.groupBox_2.setObjectName(_fromUtf8("groupBox_2"))
 87         self.textEdit = QtGui.QTextEdit(self.groupBox_2)
 88         self.textEdit.setGeometry(QtCore.QRect(20, 30, 332, 591))
 89         #結果框字體設置
 90         font = QtGui.QFont()
 91         font.setFamily(_fromUtf8("新宋體"))
 92         font.setPointSize(10)
 93         font.setBold(False)
 94         font.setWeight(50)
 95         self.textEdit.setFont(font)
 96         self.textEdit.setMidLineWidth(1)
 97         #結果框垂直滾動條設置開關
 98         self.textEdit.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
 99         # 結果框水平滾動條設置開關
100         self.textEdit.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
101         self.textEdit.setTabChangesFocus(True)
102         self.textEdit.setUndoRedoEnabled(False)
103         #結果框取消自動換行
104         self.textEdit.setLineWrapMode(QtGui.QTextEdit.NoWrap)
105         self.textEdit.setOverwriteMode(False)
106         self.textEdit.setCursorWidth(1)
107         self.textEdit.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByKeyboard | QtCore.Qt.LinksAccessibleByMouse | QtCore.Qt.TextBrowserInteraction | QtCore.Qt.TextEditable | QtCore.Qt.TextEditorInteraction | QtCore.Qt.TextSelectableByKeyboard | QtCore.Qt.TextSelectableByMouse)
108         self.textEdit.setMouseTracking(True)
109         self.textEdit.setAutoFillBackground(False)
110         self.textEdit.setObjectName(_fromUtf8("textEdit"))
111 
112         # self.customContextMenuRequested(QPoint)
113         MainWindow.setCentralWidget(self.centralwidget)
114         self.menubar = QtGui.QMenuBar(MainWindow)
115         self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
116         self.menubar.setObjectName(_fromUtf8("menubar"))
117         self.menu = QtGui.QMenu(self.menubar)
118         self.menu.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)
119         self.menu.setObjectName(_fromUtf8("menu"))
120         MainWindow.setMenuBar(self.menubar)
121         self.statusbar = QtGui.QStatusBar(MainWindow)
122         self.statusbar.setObjectName(_fromUtf8("statusbar"))
123         MainWindow.setStatusBar(self.statusbar)
124         self.action = QtGui.QAction(MainWindow)
125         self.action.setCheckable(False)
126         icon = QtGui.QIcon()
127         icon.addPixmap(QtGui.QPixmap(_fromUtf8(r"C:\Users\zg\Desktop\---\ico\Open.ico")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
128         self.action.setIcon(icon)
129         self.action.setShortcutContext(QtCore.Qt.WidgetShortcut)
130         self.action.setObjectName(_fromUtf8("action"))
131         self.action_2 = QtGui.QAction(MainWindow)
132         icon1 = QtGui.QIcon()
133         icon1.addPixmap(QtGui.QPixmap(_fromUtf8(r"C:\Users\zg\Desktop\---\ico\Log Out.ico")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
134         self.action_2.setIcon(icon1)
135         self.action_2.setObjectName(_fromUtf8("action_2"))
136         self.menu.addAction(self.action)
137         self.menu.addAction(self.action_2)
138         self.menubar.addAction(self.menu.menuAction())
139 
140         self.retranslateUi(MainWindow)
141         QtCore.QObject.connect(self.action_2, QtCore.SIGNAL(_fromUtf8("triggered()")), MainWindow.close)
142         QtCore.QObject.connect(self.action, QtCore.SIGNAL(_fromUtf8("triggered()")), self.openfile)
143         QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.soap)
144         QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL(_fromUtf8("clicked()")), self.http)
145         QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL(_fromUtf8("clicked()")), self.openfile)
146         QtCore.QObject.connect(self.pushButton_4, QtCore.SIGNAL(_fromUtf8("clicked()")), self.textEdit_2.clear)
147         QtCore.QMetaObject.connectSlotsByName(MainWindow)
148 
149     def soap(self):
150         linenum = 1
151         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'
152         last = '\n\t'+'"Snapshot=t1.inf",\n\t"ResponseParam=result",\n\tLAST );'
153         src = self.textEdit_2.toPlainText()
154         lines = src.splitlines()
155         Message = ''
156         for line in lines:
157             #判斷該行是否爲空行
158             if len(line.strip())>0:
159                 #找出每行第一個非空字符的位置
160                 num = re.search(r'\S', line).span()[0]
161                 if linenum < len(lines):
162                     #對每行進行拼接
163                     line = "\t"+line[:num] + '"' + line[num:].replace('"',r'\"').rstrip() + '"' + '\n'
164                     linenum += 1
165                 else:
166                     line = "\t"+line[:num] + '"' + line[num:].replace('"',r'\"').rstrip() + '"' + ','
167             else:
168                 line = '\n'
169                 linenum += 1
170             Message += line
171         if len(lines)>0:
172             try:
173                 Trans_Message = header + Message + last
174                 #輸出到界面
175                 self.textEdit.clear()
176                 self.textEdit.append(Trans_Message)
177             except:
178                 print("輸入錯誤")
179         else:
180             print("異常")
181     # http報文轉換
182     def http(self):
183         linenum = 1
184         header = 'web_custom_request(\n\t\"name\",\n\t\"Method=POST\",\n\t\"URL=http://{SERVERIP}:7017/ciitcmp/commserver\",\n\t\"Body=\"\n'
185         last = '\tLAST );'
186         src = self.textEdit_2.toPlainText()
187         lines = src.splitlines()
188         Message = ''
189         for line in lines:
190             # 判斷是不是空行
191             if len(line.strip()) == 0 or line.startswith('#'):
192                 continue
193                 # data = '\r\t\n'
194                 linenum += 1
195             elif len(line.strip()) > 0 and linenum < len(lines):
196                 num = re.search(r'\S', line).span()[0]
197                 data = '\t' + line[:num] + '"' + line[num:].replace('"', r'\"').rstrip() + '"' + '\n'
198                 linenum += 1
199             else:
200                 num = re.search(r'\S', line).span()[0]
201                 data = '\t' + line[:num] + '"' + line[num:].replace('"', r'\"').rstrip() + '"' + ',' + '\n'
202             Message += data
203         if len(lines)>0:
204             try:
205                 # #print(myMd5_Digest)
206                 Trans_Message = header + Message + last
207                 #輸出到界面
208                 self.textEdit.clear()
209                 self.textEdit.append(Trans_Message)
210             except:
211                 pass
212         else:
213             pass
214     #打開本地文件夾
215     def openfile(self):
216         try:
217             filename = QtGui.QFileDialog.getOpenFileName(self,"Open file","/")
218             with open(filename, 'r') as f:
219                 FileData = f.read()
220             self.textEdit_2.setPlainText(FileData)
221         except:
222             print("關閉文件對話框!")
223     def retranslateUi(self, MainWindow):
224         MainWindow.setWindowTitle(_translate("MainWindow", "文本處理工具V2.0 By:---", None))
225         MainWindow.setStatusTip(_translate("MainWindow", "文本處理工具", None))
226         self.pushButton.setStatusTip(_translate("MainWindow", "點擊將報文轉換爲soap請求", None))
227         self.pushButton.setText(_translate("MainWindow", "SOAP", None))
228         self.pushButton_2.setStatusTip(_translate("MainWindow", "點擊將報文轉換爲http請求", None))
229         self.pushButton_2.setText(_translate("MainWindow", "HTTP", None))
230         self.groupBox.setTitle(_translate("MainWindow", "報文", None))
231         self.textEdit_2.setStatusTip(_translate("MainWindow", "文本輸入框", None))
232         self.pushButton_3.setStatusTip(_translate("MainWindow", "點擊打開本地文件", None))
233         self.pushButton_3.setText(_translate("MainWindow", "Open", None))
234         self.pushButton_4.setStatusTip(_translate("MainWindow", "點擊清除文本框內容", None))
235         self.pushButton_4.setText(_translate("MainWindow", "Clear", None))
236         self.groupBox_2.setTitle(_translate("MainWindow", "結果", None))
237         self.textEdit.setStatusTip(_translate("MainWindow", "結果輸出框", None))
238         self.menu.setTitle(_translate("MainWindow", "文件", None))
239         self.action.setText(_translate("MainWindow", "打開", None))
240         self.action.setStatusTip(_translate("MainWindow", "點擊打開本地文件", None))
241         self.action.setShortcut(_translate("MainWindow", "Ctrl+D", None))
242         self.action_2.setText(_translate("MainWindow", "退出", None))
243         self.action_2.setStatusTip(_translate("MainWindow", "點擊退出程序", None))
244         self.action_2.setShortcut(_translate("MainWindow", "Ctrl+C", None))
245 if __name__ =='__main__':
246     app = QtGui.QApplication(sys.argv)
247     Form = QtGui.QMainWindow()
248     ui = Ui_MainWindow()
249     ui.setupUi(Form)
250     Form.show()
251     sys.exit(app.exec_())
2、將py文件打包成exe文件
    實現exe文件打包的工具不少,如:pyinstaller、py2exe、cxfreeze等,這裏使用cxfreeze進行文件打包,直接使用pip install pyinstaller安裝pyinstaller便可。
此時能夠爲exe文件添加本身想要的ico圖標,方法以下:
注意:將ico文件放在py文件相同目錄下,並修改xxx.spec文件(與xxx.py文件同一目錄下,相同名字的spec文件)

打開終端,執行pyinstaller xxx.specapp

生成exe文件~工具

筆者用cxfreeze進行過exe文件的打包,過程當中發生了一下,特此記錄一下~
①、安裝cxfreeze完畢後,到安裝目錄C:\Users\zg\AppData\Local\Programs\Python\Python36\Scripts\pyinstaller下,運行命令行窗口,執行命令cxfreeze,若發生如下報錯

②、需在該目錄下,建立cxfreeze.bat文件,文件內容爲學習

三、執行以下命令打包便可
cxfreeze xxx.py --target-dir=d:\dist\ --icon=d:\xxxx.ico
  以上就是就是Python PYQT4的簡單應用了,實現的功能比較簡單,後續會在進行相應的功能優化,敬請期待~~~
相關文章
相關標籤/搜索