使用PySide2库创建一个简单的十六进制文件转换工具。
1、建立界面
新建项目文件夹 hextool,然后用VSCode打开并新建ui文件夹,右键使用 New Form 使用QtDesigner建立如下界面: 然后选择菜单 窗体->View Python Code,将代码复制后保存到ui文件夹下 hextool_ui.py。
2、具体功能实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import sys from PySide2.QtWidgets import * from PySide2.QtCore import * from PySide2.QtGui import *
from ui.hextool_ui import Ui_MainWindow
class MainWindow(Ui_MainWindow,QMainWindow): def __init__(self): super(MainWindow,self).__init__() self.setupUi(self)
if __name__ == "__main__": app = QApplication(sys.argv)
mwin = MainWindow()
mwin.show()
sys.exit(app.exec_())
|
然后关联相关的按钮信号槽:
1 2 3
| self.btnChooseHex.clicked.connect(self.choose_hexfile) self.btnChooseBin.clicked.connect(self.choose_binfile) self.btnConvert.clicked.connect(self.convert_hex2bin)
|
1 2 3 4 5 6 7
| def choose_hexfile(self): self.hexfile = QFileDialog.getOpenFileName(None,"choose hex file",".","*.hex")[0] self.editHexFile.setText(self.hexfile)
def choose_binfile(self): self.binfile = QFileDialog.getSaveFileName(None,"save bin file",".","*.bin")[0] self.editBinFile.setText(self.binfile)
|
使用QFileDialog的getOpenFileName方法选择打开文件,使用getSaveFileName方法选择保存的文件。
1 2 3 4 5
| with open('dump.txt','w') as dump: self.ih.dump(dump)
with open('dump.txt','r') as dump: self.editDump.appendPlainText(dump.read())
|
这里先使用dump方法将结果保存到dump.txt文件,然后读取进行显示到编辑框中。
1 2 3 4 5 6 7 8 9 10 11
| def convert_hex2bin(self): print(f"Converting hex: {self.hexfile} to bin: {self.binfile}")
with open('dump.txt','w') as dump: self.ih.dump(dump)
with open('dump.txt','r') as dump: self.editDump.appendPlainText(dump.read())
self.ih.tobinfile(self.binfile)
|
直接使用tobinfile方法即可将文件转换并保存为bin文件。
1 2 3 4 5 6 7 8 9 10 11 12
| if __name__ == "__main__": app = QApplication(sys.argv)
dark(app)
mwin = MainWindow()
mwin.setWindowTitle("Hex2Bin file tool") win = ModernWindow(mwin) win.show()
sys.exit(app.exec_())
|
效果如下: 代码仓库:https://github.com/makerinchina-iot/Monkey-Helper-Tools-py