Python使用Pyside2和Qt Designer实现接口数据查询并生成EXE可执行文件(直接调用.ui文件和生成py调用都有)
通过Pyside2库调用QT Designer的UI文件,直接调用.ui文件和将.ui文件转换为.pt文件进行调用,调用测试成功生成exe文件
完成后的界面
一、调用ui文件版本
# coding=utf-8
from PySide2.QtWidgets import QApplication, QMainWindow, QPushButton, QPlainTextEdit, QMessageBox, QTableWidgetItem
from PySide2.QtGui import QIcon
from PySide2.QtUiTools import QUiLoader
import traceback
import requests
import os
import openpyxl
import json
from Tools.scripts.dutree import display
class Data():
def __init__(self):
super().__init__()
self.ui = QUiLoader().load('ui.ui')
# 让 表格控件宽度随着父窗口的缩放自动缩放
self.ui.tableWidget.horizontalHeader().setStretchLastSection(True)
# 设定第1列的宽度为 180像素
self.ui.tableWidget.setColumnWidth(0, 180)
# cx_Oracle.init_oracle_client(lib_dir=r'C:\Python310')
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
# 查询数据
self.ui.select_button.clicked.connect(self.selectable)
# 导出excel
self.ui.export_button.clicked.connect(self.exportexcel) # 导出excel
# 获取数据
def getdata(self):
try:
info = self.ui.cust_po_textbox.toPlainText()
print(f"获取信息:{info}")
if len(info) != 0:
url = 'http://api.xxx.com/user/v1.0/account/token' # 获取Token的接口地址
body = {
"account": "接口账号",
"password": "接口密码"
}
headers = {'content-type': "application/json"}
response = requests.post(url, data=json.dumps(body), headers=headers)
print(response.json())
json_data = response.json()['data']
# 获取result
json_result = json_data['token'] # 拿到Token
print(json_result)
url = 'http://api-xxx.com/views/table' # 获取数据的接口地址
po_list = []
for cust_po in info.splitlines():
if not cust_po.strip():
continue
cust_po = cust_po.strip()
po_list.append(cust_po)
print(f"{po_list}")
if len(po_list) == 0:
po_list = "''"
body = {
"cust_po_number": po_list
}
headers = {'content-type': "application/json",
'Authorization': 'Bearer ' + json_result}
response = requests.post(url, data=json.dumps(body), headers=headers)
print(response.json())
json_data = response.json()['data']
if len(json_data) == 0:
QMessageBox.about(self.ui, "提示", '未查询到数据!')
return json_data
else:
return json_data
else:
print("请输入合同号!")
QMessageBox.about(self.ui, "错误", '请输入合同号!')
except Exception as result:
print(f'ERROR:{result}')
QMessageBox.about(self.ui, "错误", str(result))
# 导出excel
def exportexcel(self):
try:
json_data = self.getdata()
if json_data is not None:
# workbook = openpyxl.load_workbook('try.xlsx', data_only=False)
wb = openpyxl.Workbook() # 新建工作簿
ws = wb.active # 获取工作表
ws.append(['合同号', '关单时间']) # 追加一行数据
for a in json_data:
ws.append([a['合同号'], a['LAST_UPDATE_DATE']]) # 追加一行数据
wb.save(r'文件名.xlsx') # 保存到指定路径,保存的文件必须不能处于打开状态,因为文件打开后文件只读
# ws.append(['张三', "1101", 17]) # 追加一行数据
# wb.save(r'测试1018.xlsx') # 保存到指定路径,保存的文件必须不能处于打开状态,因为文件打开后文件只读
except Exception as result:
print(f'ERROR:{result}')
QMessageBox.about(self.ui, "错误", str(result))
# 在table-widget中展示出来
def selectable(self):
try:
json_data = self.getdata()
if json_data is not None:
self.ui.tableWidget.setRowCount(len(json_data))
self.ui.tableWidget.setColumnCount(2)
self.ui.tableWidget.setHorizontalHeaderLabels(['合同号', '关单时间'])
f = 0
if len(json_data) == 0:
pass # QMessageBox.about(self.ui, "提示", '未查询到数据!')
else:
for a in json_data:
# 要插入的行始终是当前行 的下一行
self.ui.tableWidget.setItem(f, 0, QTableWidgetItem(str(a['合同号'])))
self.ui.tableWidget.setItem(f, 1, QTableWidgetItem(str(a['LAST_UPDATE_DATE'])))
f += 1
print(str(a['合同号']) + ' ' + str(a['LAST_UPDATE_DATE']))
except Exception as result:
print(f'ERROR:{result}')
QMessageBox.about(self.ui, "错误", str(result))
if __name__ == '__main__':
app = QApplication([])
gui = Data()
gui.show()
app.exec_()
二、将ui文件转为py文件进行调用
1.使用 qt designer将ui文件转为py文件
2.或者可以通过python命令进行转换(个人建议在qt designer中直接转换复制)
pyside2-uic dmeo/demo.ui > demo/Ui_Loader.py
可以直接在终端调用
参考:https://blog.csdn.net/qq_44940689/article/details/123913832
3.转换完成直接贴进主程序:
# coding=utf-8
from PySide2.QtCore import *
from PySide2.QtWidgets import *
import requests
import os
import json
from ui import Ui_MainWindow
from PySide2.QtWidgets import QApplication, QMainWindow
import openpyxl
# class LoginGui(object):
# def __init__(self):
# self = QUiLoader().load('./demo/demo')
class Data(QMainWindow, Ui_MainWindow):
def __init__(self):
super(Data, self).__init__() # 调用父类的初始化方法
self.setupUi(self) # 调用Ui_MainWindow的setupUi方法布置界面
# 让 表格控件宽度随着父窗口的缩放自动缩放
self.tableWidget.horizontalHeader().setStretchLastSection(True)
# 设定第1列的宽度为 180像素
self.tableWidget.setColumnWidth(0, 180)
# cx_Oracle.init_oracle_client(lib_dir=r'C:\Python310')
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
# 查询数据
self.select_button.clicked.connect(self.selectable)
# 导出excel
self.export_button.clicked.connect(self.exportexcel) # 导出excel
# 获取数据
def getdata(self):
try:
info = self.cust_po_textbox.toPlainText()
print(f"获取信息:{info}")
if len(info) != 0:
url = 'http://api.xxx.com/user/v1.0/account/token'
body = {
"account": "TOKEN账号",
"password": "TOKEN密码"
}
headers = {'content-type': "application/json"}
response = requests.post(url, data=json.dumps(body), headers=headers)
print(response.json())
json_data = response.json()['data']
# 获取result
json_result = json_data['token']
print(json_result)
url = 'http://api-xxx.com/views/table'
po_list = []
for cust_po in info.splitlines():
if not cust_po.strip():
continue
cust_po = cust_po.strip()
po_list.append(cust_po)
print(f"{po_list}")
if len(po_list) == 0:
po_list = "''"
body = {
"cust_po_number": po_list
}
headers = {'content-type': "application/json",
'Authorization': 'Bearer ' + json_result}
response = requests.post(url, data=json.dumps(body), headers=headers)
print(response.json())
json_data = response.json()['data']
if len(json_data) == 0:
QMessageBox.about(self, "提示", '未查询到数据!')
return json_data
else:
return json_data
else:
print("请输入合同号!")
QMessageBox.about(self, "错误", '请输入合同号!')
except Exception as result:
print(f'ERROR:{result}')
QMessageBox.about(self, "错误", str(result))
# 导出excel
def exportexcel(self):
try:
json_data = self.getdata()
if json_data is not None:
# workbook = openpyxl.load_workbook('try.xlsx', data_only=False)
wb = openpyxl.Workbook() # 新建工作簿
ws = wb.active # 获取工作表
ws.append(['合同号', '关单时间']) # 追加一行数据
for a in json_data:
ws.append([a['合同号'], a['LAST_UPDATE_DATE']]) # 追加一行数据
wb.save(r'关单数据.xlsx') # 保存到指定路径,保存的文件必须不能处于打开状态,因为文件打开后文件只读
# ws.append(['张三', "1101", 17]) # 追加一行数据
# wb.save(r'测试1018.xlsx') # 保存到指定路径,保存的文件必须不能处于打开状态,因为文件打开后文件只读
except Exception as result:
print(f'ERROR:{result}')
QMessageBox.about(self, "错误", str(result))
# 在table-widget中展示出来
def selectable(self):
try:
json_data = self.getdata()
if json_data is not None:
self.tableWidget.setRowCount(len(json_data))
self.tableWidget.setColumnCount(2)
self.tableWidget.setHorizontalHeaderLabels(['合同号', '关单时间'])
f = 0
if len(json_data) == 0:
pass # QMessageBox.about(self, "提示", '未查询到数据!')
else:
for a in json_data:
# 要插入的行始终是当前行 的下一行
self.tableWidget.setItem(f, 0, QTableWidgetItem(str(a['合同号'])))
self.tableWidget.setItem(f, 1, QTableWidgetItem(str(a['LAST_UPDATE_DATE'])))
f += 1
print(str(a['合同号']) + ' ' + str(a['LAST_UPDATE_DATE']))
except Exception as result:
print(f'ERROR:{result}')
QMessageBox.about(self, "错误", str(result))
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
if not MainWindow.objectName():
MainWindow.setObjectName(u"MainWindow")
MainWindow.resize(785, 345)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName(u"centralwidget")
self.horizontalLayout_3 = QHBoxLayout(self.centralwidget)
self.horizontalLayout_3.setObjectName(u"horizontalLayout_3")
self.groupBox = QGroupBox(self.centralwidget)
self.groupBox.setObjectName(u"groupBox")
self.horizontalLayout_2 = QHBoxLayout(self.groupBox)
self.horizontalLayout_2.setObjectName(u"horizontalLayout_2")
self.horizontalLayout = QHBoxLayout()
self.horizontalLayout.setObjectName(u"horizontalLayout")
self.cust_po_textbox = QTextEdit(self.groupBox)
self.cust_po_textbox.setObjectName(u"cust_po_textbox")
self.horizontalLayout.addWidget(self.cust_po_textbox)
self.verticalLayout = QVBoxLayout()
self.verticalLayout.setObjectName(u"verticalLayout")
self.select_button = QPushButton(self.groupBox)
self.select_button.setObjectName(u"select_button")
self.verticalLayout.addWidget(self.select_button)
self.export_button = QPushButton(self.groupBox)
self.export_button.setObjectName(u"export_button")
self.verticalLayout.addWidget(self.export_button)
self.horizontalLayout.addLayout(self.verticalLayout)
self.tableWidget = QTableWidget(self.groupBox)
if (self.tableWidget.columnCount() < 2):
self.tableWidget.setColumnCount(2)
__qtablewidgetitem = QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, __qtablewidgetitem)
__qtablewidgetitem1 = QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, __qtablewidgetitem1)
self.tableWidget.setObjectName(u"tableWidget")
self.tableWidget.setSortingEnabled(True)
self.horizontalLayout.addWidget(self.tableWidget)
self.horizontalLayout_2.addLayout(self.horizontalLayout)
self.horizontalLayout_3.addWidget(self.groupBox)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QMenuBar(MainWindow)
self.menubar.setObjectName(u"menubar")
self.menubar.setGeometry(QRect(0, 0, 785, 23))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QStatusBar(MainWindow)
self.statusbar.setObjectName(u"statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QMetaObject.connectSlotsByName(MainWindow)
# setupUi
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None))
self.groupBox.setTitle(QCoreApplication.translate("MainWindow", u"\u5173\u5355\u6570\u636e\u67e5\u8be2", None))
self.select_button.setText(QCoreApplication.translate("MainWindow", u"\u67e5\u8be2", None))
self.export_button.setText(QCoreApplication.translate("MainWindow", u"\u5bfc\u51faexcel", None))
___qtablewidgetitem = self.tableWidget.horizontalHeaderItem(0)
___qtablewidgetitem.setText(QCoreApplication.translate("MainWindow", u"\u5408\u540c\u53f7", None));
___qtablewidgetitem1 = self.tableWidget.horizontalHeaderItem(1)
___qtablewidgetitem1.setText(QCoreApplication.translate("MainWindow", u"\u5173\u5355\u65e5\u671f", None));
# retranslateUi
if __name__ == '__main__':
app = QApplication([])
gui = Data()
gui.show()
app.exec_()
三、将python文件生成EXE
直接在终端中运行
pyinstaller.exe -F -w D:\main.py --hidden-import 'pandas','requests','openpyxl'
-F 只会生成单独的一个exe文件
-w 是双击exe不会打开黑色窗口,可以试试
pyinstaller -F -w (-i icofile) 文件名.py
复制的其他大佬的图片,-i可以给exe文件直接设置图标
执行成功后得到下图这三个文件,exe文件在dist文件夹中,exe可以单独拿出来执行
双击执行文章来源:https://www.toymoban.com/news/detail-757363.html
生成后运行遇到很多奇怪的问题…忘记记录了…搞了我好几天搞醉了,第一次搞没啥经验,到处查问题文章来源地址https://www.toymoban.com/news/detail-757363.html
到了这里,关于Python使用Pyside2和Qt Designer实现接口数据查询mainwindow-tablewidget和EXCEL导出功能,并生成EXE可执行文件直接调用.ui文件和生成py调用都有-初学的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!