当前位置:   article > 正文

python 使用pyqt5实现了一个汽车配件记录系统_py车辆使用记录程序

py车辆使用记录程序

前言

老姐要求做个记录销售汽车配件得的excel,我觉得太麻烦了,身为程序员的我 必须安排一个方便快捷的系统,安排上!!!

环境要求:python3,pyqt5,pandas

1、实现效果

初始界面

b5f850f5b329435e871aed9624731d51.png

 添加界面

fc0cf94176864077a274791c5fd19578.png

2、代码实现

  1. from PyQt5.QtGui import *
  2. from PyQt5.QtWidgets import *
  3. from PyQt5.QtCore import *
  4. import pandas as pd
  5. import sys
  6. import datetime
  7. import os
  8. from shutil import copyfile
  9. class DataManage(QWidget):
  10. def __init__(self):
  11. super(DataManage, self).__init__()
  12. self.data_list = []
  13. self.base_path = r'C:\CarData'
  14. self.money_sum_text = '总金额:¥ 0.0'
  15. if not os.path.exists(self.base_path):
  16. os.mkdir(self.base_path)
  17. if not os.path.exists(self.base_path + '\data.xlsx'):
  18. file = open(self.base_path + '\data.xlsx', 'w')
  19. file.close()
  20. if os.path.exists(self.base_path + '\data.xlsx'):
  21. data = pd.read_excel(self.base_path + '\data.xlsx', dtype=str)
  22. self.money_sum_text = '总金额:¥{}'.format(str(data['销售金额'][:-1].astype(dtype='float').sum()))
  23. self.data_list = data.iloc[0:-1,:].values.tolist()
  24. self.init_ui()
  25. def init_ui(self):
  26. '''全局设置'''
  27. self.setWindowIcon(QIcon('i.ico'))
  28. self.setWindowTitle('汽车配件记录系统')
  29. self.resize(726, 440)
  30. grid = QGridLayout()
  31. '''菜单设置'''
  32. self.add_btn = QPushButton()
  33. self.add_btn.setText('添加数据')
  34. self.add_btn.setStyleSheet("background-color:#1890ff;color:white;border:none;font: 15px \"微软雅黑\";")
  35. self.add_btn.setFixedSize(100,30)
  36. self.add_btn.clicked.connect(self.add_btn_click)
  37. self.del_btn = QPushButton()
  38. self.del_btn.setText('删除数据')
  39. self.del_btn.setStyleSheet("background-color:#ff4949;color:white;border:none;font: 15px \"微软雅黑\";")
  40. self.del_btn.setFixedSize(100,30)
  41. self.del_btn.clicked.connect(self.del_data_row)
  42. self.query_btn = QPushButton()
  43. self.query_btn.setText('查询')
  44. self.query_btn.setStyleSheet("background-color:#1890ff;color:white;border:none;font: 15px \"微软雅黑\";")
  45. self.query_btn.setFixedSize(100,30)
  46. self.query_btn.clicked.connect(self.query_data_list)
  47. self.saveData_btn = QPushButton()
  48. self.saveData_btn.setText('打开文件')
  49. self.saveData_btn.setStyleSheet("background-color:#13ce66;color:white;border:none;font: 15px \"微软雅黑\";")
  50. self.saveData_btn.setFixedSize(100,30)
  51. self.saveData_btn.clicked.connect(self.saveData_data_click)
  52. self.money_sum = QLabel()
  53. self.money_sum.setText(self.money_sum_text)
  54. '''数据列表设置'''
  55. self.data_table = QTableWidget()
  56. self.data_table.setStyleSheet("QHeaderView::section{background-color:#DCDCDC;border:1px solid #D3D3D3;font: 15px \"微软雅黑\";}")
  57. COLUMN = 7
  58. ROW = 0
  59. self.data_table.setColumnCount(COLUMN)
  60. self.data_table.setRowCount(ROW)
  61. h_table_header = ['序号', '车型', '配件名称', '规格', '单价', '数量','销售金额']
  62. self.data_table.setHorizontalHeaderLabels(h_table_header)
  63. self.data_table.horizontalHeader().setDefaultAlignment(Qt.AlignVCenter)
  64. self.data_table.verticalHeader().setVisible(False)
  65. self.data_table.setShowGrid(True)
  66. self.data_table.setEditTriggers(QTableWidget.NoEditTriggers)
  67. self.data_table.setSelectionBehavior(QTableWidget.SelectRows)
  68. self.data_table.setSelectionMode(QTableWidget.SingleSelection)
  69. for index in range(self.data_table.columnCount()):
  70. headItem = self.data_table.horizontalHeaderItem(index)
  71. headItem.setTextAlignment(Qt.AlignVCenter)
  72. '''加入布局'''
  73. grid.addWidget(self.add_btn, 0, 0, 1, 1)
  74. grid.addWidget(self.del_btn, 0, 1, 1, 1)
  75. #grid.addWidget(self.query_btn, 0, 2, 1, 1)
  76. grid.addWidget(self.saveData_btn, 0, 2, 1, 1)
  77. grid.addWidget(self.money_sum, 0, 3, 1, 1)
  78. grid.addWidget(self.data_table, 1, 0, 1, 4)
  79. grid.setSpacing(12)
  80. self.setLayout(grid)
  81. # 初始化数据
  82. self.query_data_list()
  83. # 将新增数据的按钮绑定到该槽函数
  84. def add_btn_click(self):
  85. '''
  86. 打开新增数据的弹框模块
  87. :return:
  88. '''
  89. try:
  90. AddDialog.get_add_dialog(self)
  91. self.refsh_data()
  92. except PermissionError:
  93. #reply = QMessageBox.critical(self, '标题', '严重错误对话框消息正文', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
  94. QMessageBox.critical(self, "错误", "Excel文件正在打开,请关闭文件后操作!")
  95. except:
  96. QMessageBox.critical(self, "错误", "操作异常!")
  97. # 将查询数据的按钮绑定到该槽函数
  98. def query_data_list(self):
  99. '''
  100. 查询数据、并将数据展示到主窗口的数据列表中
  101. :return:
  102. '''
  103. data = self.data_list
  104. if len(data) != 0 and len(data[0]) != 0:
  105. self.data_table.setRowCount(len(data))
  106. self.data_table.setColumnCount(len(data[0]))
  107. for i in range(len(data)):
  108. for j in range(len(data[0])):
  109. self.data_table.setItem(i, j, QTableWidgetItem(str(data[i][j])))
  110. # 将删除数据按钮绑定到该槽函数
  111. def del_data_row(self):
  112. '''
  113. 删除某一行的数据信息
  114. :return:
  115. '''
  116. try:
  117. row_select = self.data_table.selectedItems()
  118. if len(row_select) != 0:
  119. row = row_select[0].row()
  120. self.data_table.removeRow(row)
  121. del self.data_list[row]
  122. self.refsh_data()
  123. except PermissionError:
  124. #reply = QMessageBox.critical(self, '标题', '严重错误对话框消息正文', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
  125. QMessageBox.critical(self, "错误", "Excel文件正在打开,请关闭文件后操作!")
  126. except:
  127. QMessageBox.critical(self, "错误", "操作异常!")
  128. # 刷新数据到文件
  129. def refsh_data(self):
  130. '''
  131. 将数据更新到文件
  132. :return:
  133. '''
  134. df = pd.DataFrame(self.data_list, columns=['序号', '车型', '配件名称', '规格', '单价', '数量','销售金额'])
  135. df['单价'].astype('float')
  136. df['数量'].astype('int')
  137. df['销售金额'].astype('float')
  138. # 保存到本地excel
  139. path = r'C:\CarData'
  140. if not os.path.exists(path):
  141. os.mkdir(r'C:\CarData')
  142. file_name = "C:\CarData\data.xlsx"
  143. if len(self.data_list) > 0:
  144. writer = pd.ExcelWriter(file_name, engine='xlsxwriter')
  145. df.to_excel(writer, sheet_name='Sheet1', index=False)
  146. workbook = writer.book
  147. worksheet = writer.sheets['Sheet1']
  148. header_format = workbook.add_format({
  149. 'bold': True, # 字体加粗
  150. 'text_wrap': True, # 是否自动换行
  151. 'valign': 'bottom', # 垂直对齐方式
  152. 'align': 'center', # 水平对齐方式
  153. 'border': 1, # 边框
  154. 'top':1, # 上边框
  155. 'left':1, # 左边框
  156. 'right':1, # 右边框
  157. 'bottom':1, # 底边框
  158. })
  159. sumMoney = 0.0
  160. for i in df['销售金额']:
  161. sumMoney += float(i)
  162. worksheet.write_string(len(self.data_list) + 1, 6, u'总金额:{}'.format(sumMoney))
  163. writer.save()
  164. writer.close()
  165. self.money_sum.setText('总金额:¥{}'.format(sumMoney))
  166. else:
  167. os.remove(file_name)
  168. self.money_sum.setText('总金额:¥0.0')
  169. # 打开文件
  170. def saveData_data_click(self):
  171. '''
  172. 打开文件
  173. :return:
  174. '''
  175. if len(self.data_list) > 0:
  176. df = pd.DataFrame(self.data_list, columns=['序号', '车型', '配件名称', '规格', '单价', '数量','销售金额'])
  177. df['单价'].astype('float')
  178. df['数量'].astype('int')
  179. df['销售金额'].astype('float')
  180. try:
  181. # 保存到文件中
  182. file_name = "C:\CarData\data.xlsx"
  183. if not os.path.exists(r'C:\CarData\copy'):
  184. os.mkdir(r'C:\CarData\copy')
  185. copyfile(file_name, "C:\CarData\copy\data_copy.xlsx")
  186. if not os.path.exists(file_name):
  187. QMessageBox.critical(self, "错误", "数据存储路径不存在,请重启系统!")
  188. os.startfile("C:\CarData\copy\data_copy.xlsx")
  189. except PermissionError:
  190. #reply = QMessageBox.critical(self, '标题', '严重错误对话框消息正文', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
  191. QMessageBox.critical(self, "错误", "Excel文件正在打开,请关闭文件后操作!")
  192. except:
  193. QMessageBox.critical(self, "错误", "操作异常!")
  194. else:
  195. QMessageBox.critical(self, "错误", "数据为空!")
  196. class AddDialog(QDialog):
  197. def __init__(self, parent=None):
  198. super(AddDialog, self).__init__(parent)
  199. self.init_ui(parent)
  200. def init_ui(self,parent):
  201. self.setWindowTitle('添加界面')
  202. self.resize(400, 200)
  203. '''水平布局'''
  204. hbox = QHBoxLayout()
  205. self.save_btn = QPushButton()
  206. self.save_btn.setText('保存')
  207. self.save_btn.setStyleSheet("background-color:#1890ff;color:white;border:none;")
  208. self.save_btn.setFixedSize(200,30)
  209. self.save_btn.clicked.connect(lambda :self.save_btn_click(parent))
  210. self.cancel_btn = QPushButton()
  211. self.cancel_btn.setText('取消')
  212. self.cancel_btn.setFixedSize(200,30)
  213. self.cancel_btn.clicked.connect(self.cancel_btn_click)
  214. hbox.addWidget(self.save_btn)
  215. hbox.addWidget(self.cancel_btn)
  216. hbox.setSpacing(12)
  217. '''校验器'''
  218. self.intvalidator = QIntValidator()
  219. self.doublevalidator = QDoubleValidator()
  220. self.doublevalidator.setDecimals(2)
  221. '''表单布局'''
  222. fbox = QFormLayout()
  223. self.seq_lab = QLabel()
  224. self.seq_lab.setText('序号:')
  225. self.seq_lab.setStyleSheet("font: 15px \"微软雅黑\";")
  226. self.seq_text = QLineEdit()
  227. self.seq_text.setFixedHeight(30)
  228. self.seq_text.setValidator(self.intvalidator)
  229. self.seq_text.setPlaceholderText('请输入序号')
  230. self.name_lab = QLabel()
  231. self.name_lab.setText('车型:')
  232. self.name_lab.setStyleSheet("font: 15px \"微软雅黑\";")
  233. self.name_text = QLineEdit()
  234. self.name_text.setFixedHeight(30)
  235. self.name_text.setPlaceholderText('请输入车型')
  236. self.age_lab = QLabel()
  237. self.age_lab.setText('配件名称:')
  238. self.age_lab.setStyleSheet("font: 15px \"微软雅黑\";")
  239. self.age_text = QLineEdit()
  240. self.age_text.setFixedHeight(30)
  241. self.age_text.setPlaceholderText('请输入配件名称')
  242. self.class_lab = QLabel()
  243. self.class_lab.setText('规格:')
  244. self.class_lab.setStyleSheet("font: 15px \"微软雅黑\";")
  245. self.class_text = QLineEdit()
  246. self.class_text.setFixedHeight(30)
  247. self.class_text.setPlaceholderText('请输入规格')
  248. self.socre_lab = QLabel()
  249. self.socre_lab.setText('单价:')
  250. self.socre_lab.setStyleSheet("font: 15px \"微软雅黑\";")
  251. self.socre_text = QLineEdit()
  252. self.socre_text.setFixedHeight(30)
  253. self.socre_text.setValidator(self.doublevalidator)
  254. self.socre_text.setPlaceholderText('请输入单价')
  255. self.num_lab = QLabel()
  256. self.num_lab.setText('数量:')
  257. self.num_lab.setStyleSheet("font: 15px \"微软雅黑\";")
  258. self.num_text = QLineEdit()
  259. self.num_text.setFixedHeight(30)
  260. self.num_text.setValidator(self.intvalidator)
  261. self.num_text.setPlaceholderText('请输入数量')
  262. self.money_lab = QLabel()
  263. self.money_lab.setText('销售金额:')
  264. self.money_lab.setStyleSheet("font: 15px \"微软雅黑\";")
  265. self.money_text = QLineEdit()
  266. self.money_text.setFixedHeight(30)
  267. self.money_text.setValidator(self.doublevalidator)
  268. self.money_text.setPlaceholderText('请输入销售金额')
  269. fbox.addRow(self.seq_lab,self.seq_text)
  270. fbox.addRow(self.name_lab, self.name_text)
  271. fbox.addRow(self.age_lab, self.age_text)
  272. fbox.addRow(self.class_lab, self.class_text)
  273. fbox.addRow(self.socre_lab, self.socre_text)
  274. fbox.addRow(self.num_lab, self.num_text)
  275. fbox.addRow(self.money_lab, self.money_text)
  276. fbox.setSpacing(12)
  277. vbox = QVBoxLayout()
  278. vbox.addLayout(fbox)
  279. vbox.addLayout(hbox)
  280. self.setLayout(vbox)
  281. def save_btn_click(self,parent):
  282. if self.seq_text.text().strip() != '' and self.name_text.text().strip() != '' \
  283. and self.age_text.text().strip() != ''and self.class_text.text().strip() != '' \
  284. and self.socre_text.text().strip() != '' and self.num_text.text().strip() != '' \
  285. and self.money_text.text().strip() != '':
  286. data = [self.seq_text.text(),
  287. self.name_text.text(),
  288. self.age_text.text(),
  289. self.class_text.text(),
  290. self.socre_text.text(),
  291. self.num_text.text(),
  292. self.money_text.text()]
  293. parent.data_list.append(data)
  294. parent.query_data_list()
  295. self.close()
  296. def cancel_btn_click(self):
  297. self.close()
  298. @staticmethod
  299. def get_add_dialog(parent=None):
  300. dialog = AddDialog(parent)
  301. return dialog.exec()
  302. if __name__ == '__main__':
  303. app = QApplication(sys.argv)
  304. main = DataManage()
  305. main.show()
  306. sys.exit(app.exec_())

 3、pyinstaller打包成exe

pyinstaller -F -w main.py --icon=i.ico

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/307780
推荐阅读
相关标签
  

闽ICP备14008679号