Python使用Pyside2和Qt Designer實(shí)現(xiàn)接口數(shù)據(jù)查詢并生成EXE可執(zhí)行文件(直接調(diào)用.ui文件和生成py調(diào)用都有)
通過(guò)Pyside2庫(kù)調(diào)用QT Designer的UI文件,直接調(diào)用.ui文件和將.ui文件轉(zhuǎn)換為.pt文件進(jìn)行調(diào)用,調(diào)用測(cè)試成功生成exe文件
完成后的界面
一、調(diào)用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')
# 讓 表格控件寬度隨著父窗口的縮放自動(dòng)縮放
self.ui.tableWidget.horizontalHeader().setStretchLastSection(True)
# 設(shè)定第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'
# 查詢數(shù)據(jù)
self.ui.select_button.clicked.connect(self.selectable)
# 導(dǎo)出excel
self.ui.export_button.clicked.connect(self.exportexcel) # 導(dǎo)出excel
# 獲取數(shù)據(jù)
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": "接口賬號(hào)",
"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' # 獲取數(shù)據(jù)的接口地址
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, "提示", '未查詢到數(shù)據(jù)!')
return json_data
else:
return json_data
else:
print("請(qǐng)輸入合同號(hào)!")
QMessageBox.about(self.ui, "錯(cuò)誤", '請(qǐng)輸入合同號(hào)!')
except Exception as result:
print(f'ERROR:{result}')
QMessageBox.about(self.ui, "錯(cuò)誤", str(result))
# 導(dǎo)出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(['合同號(hào)', '關(guān)單時(shí)間']) # 追加一行數(shù)據(jù)
for a in json_data:
ws.append([a['合同號(hào)'], a['LAST_UPDATE_DATE']]) # 追加一行數(shù)據(jù)
wb.save(r'文件名.xlsx') # 保存到指定路徑,保存的文件必須不能處于打開狀態(tài),因?yàn)槲募蜷_后文件只讀
# ws.append(['張三', "1101", 17]) # 追加一行數(shù)據(jù)
# wb.save(r'測(cè)試1018.xlsx') # 保存到指定路徑,保存的文件必須不能處于打開狀態(tài),因?yàn)槲募蜷_后文件只讀
except Exception as result:
print(f'ERROR:{result}')
QMessageBox.about(self.ui, "錯(cuò)誤", str(result))
# 在table-widget中展示出來(lái)
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(['合同號(hào)', '關(guān)單時(shí)間'])
f = 0
if len(json_data) == 0:
pass # QMessageBox.about(self.ui, "提示", '未查詢到數(shù)據(jù)!')
else:
for a in json_data:
# 要插入的行始終是當(dāng)前行 的下一行
self.ui.tableWidget.setItem(f, 0, QTableWidgetItem(str(a['合同號(hào)'])))
self.ui.tableWidget.setItem(f, 1, QTableWidgetItem(str(a['LAST_UPDATE_DATE'])))
f += 1
print(str(a['合同號(hào)']) + ' ' + str(a['LAST_UPDATE_DATE']))
except Exception as result:
print(f'ERROR:{result}')
QMessageBox.about(self.ui, "錯(cuò)誤", str(result))
if __name__ == '__main__':
app = QApplication([])
gui = Data()
gui.show()
app.exec_()
二、將ui文件轉(zhuǎn)為py文件進(jìn)行調(diào)用
1.使用 qt designer將ui文件轉(zhuǎn)為py文件
2.或者可以通過(guò)python命令進(jìn)行轉(zhuǎn)換(個(gè)人建議在qt designer中直接轉(zhuǎn)換復(fù)制)
pyside2-uic dmeo/demo.ui > demo/Ui_Loader.py
可以直接在終端調(diào)用
參考:https://blog.csdn.net/qq_44940689/article/details/123913832
3.轉(zhuǎn)換完成直接貼進(jìn)主程序:
# 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__() # 調(diào)用父類的初始化方法
self.setupUi(self) # 調(diào)用Ui_MainWindow的setupUi方法布置界面
# 讓 表格控件寬度隨著父窗口的縮放自動(dòng)縮放
self.tableWidget.horizontalHeader().setStretchLastSection(True)
# 設(shè)定第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'
# 查詢數(shù)據(jù)
self.select_button.clicked.connect(self.selectable)
# 導(dǎo)出excel
self.export_button.clicked.connect(self.exportexcel) # 導(dǎo)出excel
# 獲取數(shù)據(jù)
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賬號(hào)",
"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, "提示", '未查詢到數(shù)據(jù)!')
return json_data
else:
return json_data
else:
print("請(qǐng)輸入合同號(hào)!")
QMessageBox.about(self, "錯(cuò)誤", '請(qǐng)輸入合同號(hào)!')
except Exception as result:
print(f'ERROR:{result}')
QMessageBox.about(self, "錯(cuò)誤", str(result))
# 導(dǎo)出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(['合同號(hào)', '關(guān)單時(shí)間']) # 追加一行數(shù)據(jù)
for a in json_data:
ws.append([a['合同號(hào)'], a['LAST_UPDATE_DATE']]) # 追加一行數(shù)據(jù)
wb.save(r'關(guān)單數(shù)據(jù).xlsx') # 保存到指定路徑,保存的文件必須不能處于打開狀態(tài),因?yàn)槲募蜷_后文件只讀
# ws.append(['張三', "1101", 17]) # 追加一行數(shù)據(jù)
# wb.save(r'測(cè)試1018.xlsx') # 保存到指定路徑,保存的文件必須不能處于打開狀態(tài),因?yàn)槲募蜷_后文件只讀
except Exception as result:
print(f'ERROR:{result}')
QMessageBox.about(self, "錯(cuò)誤", str(result))
# 在table-widget中展示出來(lái)
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(['合同號(hào)', '關(guān)單時(shí)間'])
f = 0
if len(json_data) == 0:
pass # QMessageBox.about(self, "提示", '未查詢到數(shù)據(jù)!')
else:
for a in json_data:
# 要插入的行始終是當(dāng)前行 的下一行
self.tableWidget.setItem(f, 0, QTableWidgetItem(str(a['合同號(hào)'])))
self.tableWidget.setItem(f, 1, QTableWidgetItem(str(a['LAST_UPDATE_DATE'])))
f += 1
print(str(a['合同號(hào)']) + ' ' + str(a['LAST_UPDATE_DATE']))
except Exception as result:
print(f'ERROR:{result}')
QMessageBox.about(self, "錯(cuò)誤", 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
直接在終端中運(yùn)行
pyinstaller.exe -F -w D:\main.py --hidden-import 'pandas','requests','openpyxl'
-F 只會(huì)生成單獨(dú)的一個(gè)exe文件
-w 是雙擊exe不會(huì)打開黑色窗口,可以試試
pyinstaller -F -w (-i icofile) 文件名.py
復(fù)制的其他大佬的圖片,-i可以給exe文件直接設(shè)置圖標(biāo)
執(zhí)行成功后得到下圖這三個(gè)文件,exe文件在dist文件夾中,exe可以單獨(dú)拿出來(lái)執(zhí)行
雙擊執(zhí)行文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-757363.html
生成后運(yùn)行遇到很多奇怪的問(wèn)題…忘記記錄了…搞了我好幾天搞醉了,第一次搞沒啥經(jīng)驗(yàn),到處查問(wèn)題文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-757363.html
到了這里,關(guān)于Python使用Pyside2和Qt Designer實(shí)現(xiàn)接口數(shù)據(jù)查詢mainwindow-tablewidget和EXCEL導(dǎo)出功能,并生成EXE可執(zhí)行文件直接調(diào)用.ui文件和生成py調(diào)用都有-初學(xué)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!