一、工作中,有一個關鍵詞查找工作,查找開發版本中使用的文本,有哪些詞語是非法的,一個一個去查太累了,所以想到了用代碼來實現。可后來想想,能否做成簡單的小工具,大家都可以使用。
於是就着手編寫工具。原來是計划用Python自帶的lib庫:tkinter,寫的時候發現真不好操作,網上對應的說明文檔也比較少。所以查找了好久,決定用PyQt5來實現。
二、大概思路:①.使用designer.exe繪制窗體;②使用eric6生成主窗口對應的py文件;③編輯調用主窗口的程序;④使用信號(signal)和槽(slot)機制建立窗體的動作指令;⑤調試打包
三、實現過程
1.PyQt5的安裝上篇已做介紹,打開designer.exe,新建一個ui文件。如圖,放置了3個QPushButton,然后放置了QLineEdit和QTextEdit,第一個設置了默認文本(placeholderText設置),保存為openfile.ui

2.在eric6中,先創建一個項目,在forms窗體,添加openfile.ui,然后編譯,生成Ui_openfile.py,如下附錄2中的代碼
3.創建主程序openfile.py,導入界面程序:from Ui_openfile import *,然后再導入其他需要的庫。
4.編寫類class,定義其中關於界面點擊的函數
類(Class): 用來描述具有相同的屬性和方法的對象的集合。它定義了該集合中每個對象所共有的屬性和方法。對象是類的實例。方法:類中定義的函數。
5.定義方法:findtxt,主要實現查找已有文本,是否在目標文件中。方法findtxt是一個槽函數,要與前面的信號關聯起來。所以在前面的Ui_openfile.py,添加信號語句:self.button_find.clicked.connect(self.findtxt),這樣信號和槽就關聯起來了。
在獲取目標文件時,需要打開一個文件選擇框。此時定義了另一個函數:loadtxt,實現打開文件選擇控件,獲取文本內容,並把目標文件的路徑寫在下方的文本框里。使用方法:self.loadtxt()來調用類中的另一個函數,獲取目標文件內容。
(另外:方法loadtxt也可以成為一個槽函數,要與前面的信號關聯起來。可以在前面的Ui_openfile.py,添加信號語句:self.button_openfile.clicked.connect(self.loadtxt),進行信號和槽的關聯)
當查找完畢后,可以在findtxt后面添加語句: self.lineEdit.setText('結果已保存在D盤list.txt文件')。這樣就可以做到通知執行結果的作用。
6.同樣的,定義方法:listappear。實現獲取關鍵詞文本內容並顯示。然后在前面添加信號:self.button_keylist.clicked.connect(self.listappear),進行信號和槽函數的關聯。
7.編寫完畢后,檢查無問題,CMD窗口執行語句:Python openfile.py ,會自動調用Ui_openfile.py,這樣一個小工具就初步告成了。
8.編譯打包。有多個py文件時,主文件放在前面即可,打包命令:C:\Users\admin\AppData\Local\Programs\Python\Python37\Scripts>pyinstaller -F openfile.py Ui_openfile.py
打包后生成exe文件,打開是閃退,提示錯誤: ImportError: unable to find Qt5Core.dll on PATH
經過查找,參考博客 https://blog.csdn.net/zwyact/article/details/99778898 ,添加一小段代碼后解決。

四.附錄程序,注意縮進時,同一文本縮進方式要保持一致(TAB間縮進和四個空格縮進,只用一種)會省去編譯報錯的困擾:
報錯信息:IndentationError: unexpected indent;IndentationError: expected an indented block
解決辦法,可以用文本編輯器Notepad++把當前python腳本的所有空格或Tab字符都顯示出來查看,視圖 -> 顯示符號 -> 顯示空格與制表符,這樣就能看到縮進方式了。
.主程序,很多異常都未寫出來,后面逐步優化
import sys,os
if hasattr(sys, 'frozen'):
os.environ['PATH'] = sys._MEIPASS + ";" + os.environ['PATH']
from PyQt5.QtWidgets import *
from Ui_openfile import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
file='//19.87.8.11/testtools/keywords.txt'
class MyMainWindow(QMainWindow,Ui_mainWindow):
def __init__(self,parent=None):
super(MyMainWindow,self).__init__(parent)
self.setupUi(self)
def loadtxt(self): #打開文本選擇路徑框,獲取目標文本
filename,_=QFileDialog.getOpenFileName(self,'open file','.','txt(*.txt)') #QFileDialog是用於打開和保存文件的標准對話框
def readtext(filename): #讀取文本內容
fullText = []
textcon = open(filename, 'r', encoding='utf-8') #使用utf-8編碼打開,非此編碼的文本打開有問題,可以采用忽略錯誤的方式
for i in textcon:
lincone = i.strip()
fullText.append(lincone)
#print(fullText)
return '\n'.join(fullText)
textcon.close()
if filename:
cur_path=QDir('.')
relative_path = cur_path.relativeFilePath(filename)
self.folderlist.setText(relative_path) #顯示獲取文本的路徑
self.goal=readtext(filename)
def findtxt(self):
j=0
text_con=open(file, 'r', encoding='utf-8') #關鍵詞所在的文本
self.loadtxt() #調用獲取目標文本內容函數
goal_con=self.goal
for i in text_con:
line_cone = i.strip()
#print(line_cone)
j = j + 1
if line_cone in goal_con: #主程序中的關鍵程序,寫了那么多,其他都是為了這個服務,南啊
f=open('d:/list.txt','a',encoding='utf-8')
f.write(str(j)+line_cone+'\n')
self.lineEdit.setText('結果已保存在D盤list.txt文件') #結果提示
def listappear(self): #獲取關鍵詞文本內容,展示出來。
fullText = ''
textcon = open(file, 'r', encoding='utf-8')
for i in textcon:
lincone = i.strip()
fullText=fullText+lincone+','
self.keylist.setText(fullText) #設置的文本內容是個字符串,所以不能用前面的列表形式收集。
textcon.close()
if __name__=="__main__":
app=QApplication(sys.argv)
myWin=MyMainWindow()
myWin.show()
sys.exit(app.exec_())
2.ui文件
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'D:\1.soft\88.Python-Eric\eric6work\secondwindow.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_mainWindow(object):
def setupUi(self, mainWindow):
mainWindow.setObjectName("mainWindow")
mainWindow.resize(662, 430)
self.centralwidget = QtWidgets.QWidget(mainWindow)
self.centralwidget.setObjectName("centralwidget")
self.button_keylist = QtWidgets.QPushButton(self.centralwidget)
self.button_keylist.setGeometry(QtCore.QRect(80, 160, 121, 41))
self.button_keylist.setObjectName("button_keylist")
self.keylist = QtWidgets.QTextEdit(self.centralwidget)
self.keylist.setGeometry(QtCore.QRect(230, 160, 251, 151))
self.keylist.setObjectName("keylist")
self.folderlist = QtWidgets.QLineEdit(self.centralwidget)
self.folderlist.setGeometry(QtCore.QRect(230, 100, 401, 31))
self.folderlist.setObjectName("folderlist")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(230, 40, 241, 31))
self.lineEdit.setObjectName("lineEdit")
self.button_find = QtWidgets.QPushButton(self.centralwidget)
self.button_find.setGeometry(QtCore.QRect(80, 40, 121, 31))
self.button_find.setObjectName("button_find")
self.button_openfile = QtWidgets.QPushButton(self.centralwidget)
self.button_openfile.setGeometry(QtCore.QRect(80, 100, 121, 31))
self.button_openfile.setObjectName("button_openfile")
mainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(mainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 662, 23))
self.menubar.setObjectName("menubar")
mainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(mainWindow)
self.statusbar.setObjectName("statusbar")
mainWindow.setStatusBar(self.statusbar)
self.retranslateUi(mainWindow)
self.button_find.clicked.connect(self.findtxt) #信號signal
self.button_keylist.clicked.connect(self.listappear) #信號signal
QtCore.QMetaObject.connectSlotsByName(mainWindow)
def retranslateUi(self, mainWindow):
_translate = QtCore.QCoreApplication.translate
mainWindow.setWindowTitle(_translate("mainWindow", "關鍵字查詢V1.0"))
self.button_keylist.setText(_translate("mainWindow", "當前已有關鍵詞"))
self.lineEdit.setPlaceholderText(_translate("mainWindow", "結果保存在D盤list文本文件"))
self.button_find.setText(_translate("mainWindow", "查找"))
self.button_openfile.setText(_translate("mainWindow", "目標文件路徑"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
mainWindow = QtWidgets.QMainWindow()
ui = Ui_mainWindow()
ui.setupUi(mainWindow)
mainWindow.show()
sys.exit(app.exec_())
