程序示例精选
Python+QT停车场车牌识别计费管理系统-升级版
如需安装运行环境或远程调试,见文章底部个人QQ名片,由专业技术人员远程协助!
前言
这篇博客针对<<Python+QT停车场车牌识别计费管理系统-升级版>>编写代码,代码整洁,规则,易读。 学习与应用推荐首选。
主要升级内容如下:
此版本优化了通过秒计算的计费精确度,添加了二维码扫码支付功能,以及车位数量,剩余车位,等信息。
文章目录
一、所需工具软件
二、使用步骤
1. 引入库
2. 代码实现
3. 运行结果
三、在线协助
一、所需工具软件
1. Python,Pycharm
2. OpenCV
二、使用步骤
1.引入库
# coding:utf-8
import sys
import os
import csv
import cv2
import numpy as np
from PIL import Image, ImageTk
from tensorflow import keras
from core import locate_and_correct
from Unet import unet_predict
from CNN import cnn_predict
from untitled import Ui_mainWindow
import record
import photoW
from dbase import Record2
from PyQt5 import QtWidgets
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from login import *
from register import *
import time
import datetime
from datetime import datetime
import pandas as pd
import time
2. 代码实现
代码如下:
class myWin(QtWidgets.QMainWindow, Ui_mainWindow):
def __init__(self):
super(myWin, self).__init__()
self.setupUi(self)
self.pushButton_5.clicked.connect(self.carPlateRecogIn)
self.pushButton_9.clicked.connect(self.carPlatePosition)
self.pushButton_10.clicked.connect(self.manualOpen)
self.pushButton_11.clicked.connect(self.CostCalculation)
self.pushButton_3.clicked.connect(self.open_second_ui)
self.unet = keras.models.load_model('unet.h5')
self.cnn = keras.models.load_model('cnn.h5')
print('正在启动中,请稍等...')
cnn_predict(self.cnn, [np.zeros((80, 240, 3))])
print("已启动,开始识别!")
self.currentNumberInit()
self.vipNumberInit()
self.pushButton.clicked.connect(self.totalQttyModify)
self.pushButton_2.clicked.connect(self.appointmentModify)
self.pushButton_4.clicked.connect(self.feeModify)
self.pushButton_12.clicked.connect(self.vipAdd)
self.pushButton_12.clicked.connect(self.vipAdd)
self.pushButton_13.clicked.connect(self.clearpN)
self.pushButton_7.clicked.connect(self.threadRun)
#self.pushButton_3.clicked.connect(self.threadRun)
self.pushButton_2.clicked.connect(self.closeEvent)
self.pushButton_8.clicked.connect(self.switch_video)
self.timer2 = VideoTimer()
self.timer2.timeSignal.signal[str].connect(self.videoRecog2)
def threadRun(self):
# thread1.start()
if self.pushButton_7.text()=="模型初始化thread":
threadSetup()
# thread1.start()
self.pushButton_7.setText("停止模型thread")
elif self.pushButton_7.text()=="停止模型thread":
#stop_thread(thread1)
#stop_thread(threadT)
threadStop()
print("tttt6")
self.pushButton_7.setText("模型初始化thread")
# # 退出系统窗口 X 绑定函数事件
def closeEvent(self, event):
# print("test")
self.box = QMessageBox(QMessageBox.Warning, "系统提示信息", "是否退出系统?")
qyes = self.box.addButton(self.tr("是"), QMessageBox.YesRole)
qno = self.box.addButton(self.tr("否"), QMessageBox.NoRole)
self.box.exec_()
if self.box.clickedButton() == qyes:
try:
threadStop()
except:
print("abnormal")
event.accept()
QtWidgets.QWidget.closeEvent(self, event)
sys.exit().accept()
else:
event.ignore()
def switch_video(self):
# self.timer2.start()
if self.pushButton_8.text() == "开始检测":
self.timer2.start()
print("tttt6")
self.pushButton_8.setText("暂停检测")
elif self.pushButton_8.text() == "暂停检测":
self.timer2.stop()
print("tttt6")
self.pushButton_8.setText("开始检测")
def videoRecog2(self):
# print("im02: ",im02)
try:
# 视频1开始***********************************************
frame = cv2.cvtColor(im02, cv2.COLOR_BGR2RGB)
height, width, bytesPerComponent = frame.shape
bytesPerLine = bytesPerComponent * width
self.q_image = QtGui.QImage(frame.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888) \
.scaled(self.label.height() * 0.8, self.label.height() * 0.6)
self.label.setPixmap(QPixmap.fromImage(self.q_image))
#self.label.setScaledContents(True)
self.update()
# 视频1结束***********************************************
# 视频2开始***********************************************
cv2.imwrite("tempV.jpg",im02)
self.img_src_path="tempV.jpg"
print("test")
img_src = cv2.imdecode(np.fromfile(self.img_src_path, dtype=np.uint8), -1) # 从中文路径读取时用
print("test")
h, w = img_src.shape[0], img_src.shape[1]
print("aa")
if h * w <= 240 * 80 and 2 <= w / h <= 5: # 满足该条件说明可能整个图片就是一张车牌,无需定位,直接识别即可
lic = cv2.resize(img_src, dsize=(240, 80), interpolation=cv2.INTER_AREA)[:, :, :3] # 直接resize为(240,80)
img_src_copy, Lic_img = img_src, [lic]
else: # 否则就需通过unet对img_src原图预测,得到img_mask,实现车牌定位,然后进行识别
img_src, img_mask = unet_predict(self.unet, self.img_src_path)
img_src_copy, Lic_img = locate_and_correct(img_src, img_mask) # 利用core.py中的locate_and_correct函数进行车牌定位和矫正
print("aa")
Lic_pred = cnn_predict(self.cnn, Lic_img) # 利用cnn进行车牌的识别预测,Lic_pred中存的是元祖(车牌图片,识别结果)
if Lic_pred:
#img = Image.fromarray(img_src_copy[:, :, ::-1]) # img_src_copy[:, :, ::-1]将BGR转为RGB
# self.img_Tk = ImageTk.PhotoImage(img)
# self.can_src.delete('all') # 显示前,先清空画板
#self.can_src.create_image(258, 258, image=self.img_Tk,anchor='center') # img_src_copy上绘制出了定位的车牌轮廓,将其显示在画板上
# 显示相片到label_2
img = cv2.imread("tempV.jpg")
frame = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
height, width, bytesPerComponent = frame.shape
bytesPerLine = bytesPerComponent * width
self.q_image = QtGui.QImage(frame.data, width, height, bytesPerLine, QtGui.QImage.Format_RGB888) \
.scaled(self.label.height() * 0.8, self.label.height() * 0.6)
self.label.setPixmap(QPixmap.fromImage(self.q_image))
self.update()
for i, lic_pred in enumerate(Lic_pred):
if i == 0:
print("i: ", i)
print("lic_pred[1]: ",lic_pred[1])
# self.textEdit.setPlainText("车牌编号:"+lic_pred[1])
elif i == 1:
print("i: ", i)
# self.textEdit.setPlainText("车牌编号:"+lic_pred[1])
elif i == 2:
print("i: ", i)
# self.textEdit.setPlainText("车牌编号:"+lic_pred[1])
plateNumber=lic_pred[1]
print("lic_pred[1]2: ", lic_pred[1])
if len(plateNumber)>5:
if not os.path.exists("pN.jpg"):
cv2.imwrite("pN.jpg",im02)
msg_box = QMessageBox(QMessageBox.Warning, '信息', '检测到有车辆到达门口')
msg_box.exec_()
except:
print("mistake")
#软件启动后显示数据库中当前剩余车位数量,与总车位数量到界面
def currentNumberInit(self):
print("aa")
if os.path.exists('pN.jpg'):
os.remove("pN.jpg")
#得到recordinfo.db中在场车辆总数
conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
curr = conn.cursor()
curr.execute('select name from record_plate')
result2 = curr.fetchall()
row = len(result2)
print("row:", row)
inSiteNumber = row
conn.commit()
curr.close()
conn.close()
conn = sqlite3.connect(databaseName, check_same_thread=False)
curr = conn.cursor()
curr.execute("select * from parking_spaces_number")
# curr.execute("select record_date from {}".format(tableName) )
results = curr.fetchall()
print("results",results[0])
name_list = []
for i in results:
i = list(i)
print(i)
print(i[1])
print(i[2])
print(i[3])
# print(i[4])
print(i[5])
self.lineEdit_2.setText(i[1])
self.lineEdit_3.setText(str(int(i[1])-int(i[3])-inSiteNumber))
self.lineEdit_4.setText(i[3])
self.lineEdit_5.setText(str(inSiteNumber))
self.lineEdit.setText(i[5])
conn.commit()
curr.close()
conn.close()
def currentNumberInit2(self):
print("aa")
#得到recordinfo.db中在场车辆总数
conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
curr = conn.cursor()
curr.execute('select name from record_plate')
result2 = curr.fetchall()
row = len(result2)
print("row:", row)
inSiteNumber = row
conn.commit()
curr.close()
conn.close()
conn = sqlite3.connect(databaseName, check_same_thread=False)
curr = conn.cursor()
curr.execute("select * from parking_spaces_number")
# curr.execute("select record_date from {}".format(tableName) )
results = curr.fetchall()
print("results",results[0])
name_list = []
for i in results:
i = list(i)
print(i)
print(i[1])
print(i[2])
print(i[3])
# print(i[4])
print(i[5])
self.lineEdit_2.setText(i[1])
self.lineEdit_3.setText(str(int(i[1])-int(i[3])-inSiteNumber))
self.lineEdit_4.setText(i[3])
self.lineEdit_5.setText(str(inSiteNumber))
self.lineEdit.setText(i[5])
conn.commit()
curr.close()
conn.close()
#软件启动后显示数据库中vip车辆到界面
def vipNumberInit(self):
print("aa")
try:
#得到recordinfo.db中在场车辆总数
conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
curr = conn.cursor()
curr.execute('select name from vip')
result2 = curr.fetchall()
row = len(result2)
print("row:", row)
vipNumber = row
conn.commit()
curr.close()
conn.close()
conn = sqlite3.connect(databaseName, check_same_thread=False)
curr = conn.cursor()
curr.execute("select * from vip")
# curr.execute("select record_date from {}".format(tableName) )
results = curr.fetchall()
print("results",results[0])
name_list = []
for i in results:
i = list(i)
print(i)
print(i[1])
self.textEdit_4.setPlainText(i[1])
conn.commit()
curr.close()
conn.close()
except:
print("mistake")
#清空pN
def clearpN(self):
if os.path.exists('pN.jpg'):
os.remove("pN.jpg")
#vip添加
def vipAdd(self):
TEXT=self.lineEdit_6.text()
import dbase
import sqlite3
import datetime
from datetime import datetime
conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
curr = conn.cursor()
curr.execute("select * from vip")
# curr.execute("select record_date from {}".format(tableName) )
results = curr.fetchall()
# 数组包含某个文字判断
name_list = []
for i in results:
i = list(i)
print(i)
name_list += i
# name_list =','.join(i)
print("name_list2", name_list)
print("name_list type", type(name_list))
if TEXT not in name_list:
print("yes")
# curr.execute("select name from record_table")
print("saa1")
curr.execute('insert into vip values (null, ?, ?, ?, ?, ?)',(TEXT, datetime.now().strftime("%Y%m%d %H:%M:%S"), ' ', ' ', ' '))
print("saa2")
conn.commit()
conn.rollback()
curr.close()
conn.close()
self.vipNumberInit()
# 界面修改总车位数量写入数据库
def totalQttyModify(self):
totalQtty = self.lineEdit_2.text() #总车位数读取
print("totalQtty",totalQtty)
conn = sqlite3.connect(databaseName, check_same_thread=False)
curr = conn.cursor()
curr.execute('update parking_spaces_number set total_parking_spaces_qtty = "' + str(int(totalQtty)) + '"')
print("enDone")
conn.commit()
curr.close()
conn.close()
msg_box = QMessageBox(QMessageBox.Warning, '信息', '修改成功')
msg_box.exec_()
#界面预约车位数量写入数据库
def appointmentModify(self):
appointmentQtty = self.lineEdit_4.text()
print("appointmentQtty", appointmentQtty)
conn = sqlite3.connect(databaseName, check_same_thread=False)
curr = conn.cursor()
curr.execute('update parking_spaces_number set appointment_qtty = "' + str(int(appointmentQtty)) + '"')
print("enDone")
conn.commit()
curr.close()
conn.close()
self.currentNumberInit()
msg_box = QMessageBox(QMessageBox.Warning, '信息', '预约成功')
msg_box.exec_()
#界面预约车位数量写入数据库
def feeModify(self):
feeT = self.lineEdit.text()
print("feeT", feeT)
conn = sqlite3.connect(databaseName, check_same_thread=False)
curr = conn.cursor()
curr.execute('update parking_spaces_number set fee_num = "' + feeT + '"')
print("enDone")
conn.commit()
curr.close()
conn.close()
msg_box = QMessageBox(QMessageBox.Warning, '信息', '每小时计费修改成功')
msg_box.exec_()
def displayPlate(self):
# 显示相片到label_2
imgName, imgType = QFileDialog.getOpenFileName(self,"打开文件","./","files(*.*)")
img = cv2.imread(imgName)
#img = cv2.imread("test_img/aa.jpg")
cv2.imwrite('temp.jpg', img)
height, width, pixels = img.shape
if width > (self.label.width()):
rheight = (self.label.width() * height) * width
rwidth = self.label.width()
elif height > (self.label.height()):
rwidth = (self.label.height() * width) / height
rheight = self.label.height()
elif ((self.label.height()) - height) < ((self.label.width()) - width):
rwidth = (self.label.height() * width) / height
rheight = self.label.height()
else:
rheight = height
rwidth = width
frame = cv2.resize(img, (int(rwidth), int(rheight)))
img2 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # opencv读取的bgr格式图片转换成rgb格式
_image = QtGui.QImage(img2[:], img2.shape[1], img2.shape[0], img2.shape[1] * 3, QtGui.QImage.Format_RGB888)
jpg_out = QtGui.QPixmap(_image).scaled(rwidth, rheight) # 设置图片大小
self.label.setPixmap(jpg_out) # 设置图片显示
def carPlatePosition(self):
self.label_7.clear()
print("carPlateRecog start")
self.img_src_path="pN.jpg"
img_src = cv2.imdecode(np.fromfile(self.img_src_path, dtype=np.uint8), -1) # 从中文路径读取时用
h, w = img_src.shape[0], img_src.shape[1]
print("aa")
if h * w <= 240 * 80 and 2 <= w / h <= 5: # 满足该条件说明可能整个图片就是一张车牌,无需定位,直接识别即可
lic = cv2.resize(img_src, dsize=(240, 80), interpolation=cv2.INTER_AREA)[:, :, :3] # 直接resize为(240,80)
img_src_copy, Lic_img = img_src, [lic]
else: # 否则就需通过unet对img_src原图预测,得到img_mask,实现车牌定位,然后进行识别
img_src, img_mask = unet_predict(self.unet, self.img_src_path)
img_src_copy, Lic_img = locate_and_correct(img_src, img_mask) # 利用core.py中的locate_and_correct函数进行车牌定位和矫正
print("aa")
def carPlateRecogOut(self):
print("carPlateRecog start")
# self.label_7.clear()
self.img_src_path="pN.jpg"
img_src = cv2.imdecode(np.fromfile(self.img_src_path, dtype=np.uint8), -1) # 从中文路径读取时用
h, w = img_src.shape[0], img_src.shape[1]
print("aa")
if h * w <= 240 * 80 and 2 <= w / h <= 5: # 满足该条件说明可能整个图片就是一张车牌,无需定位,直接识别即可
lic = cv2.resize(img_src, dsize=(240, 80), interpolation=cv2.INTER_AREA)[:, :, :3] # 直接resize为(240,80)
img_src_copy, Lic_img = img_src, [lic]
else: # 否则就需通过unet对img_src原图预测,得到img_mask,实现车牌定位,然后进行识别
img_src, img_mask = unet_predict(self.unet, self.img_src_path)
img_src_copy, Lic_img = locate_and_correct(img_src, img_mask) # 利用core.py中的locate_and_correct函数进行车牌定位和矫正
print("aa")
Lic_pred = cnn_predict(self.cnn, Lic_img) # 利用cnn进行车牌的识别预测,Lic_pred中存的是元祖(车牌图片,识别结果)
if Lic_pred:
# 显示相片到label_2
img = cv2.imread("pN.jpg")
self.label_7.setPixmap(QPixmap(""))
height, width, pixels = img.shape
if width > (self.label_7.width()):
rheight = (self.label_7.width() * height) * width
rwidth = self.label_7.width()
elif height > (self.label_7.height()):
rwidth = (self.label_7.height() * width) / height
rheight = self.label_7.height()
elif ((self.label_7.height()) - height) < ((self.label_7.width()) - width):
rwidth = (self.label_7.height() * width) / height
rheight = self.label_7.height()
else:
rheight = height
rwidth = width
frame = cv2.resize(img, (int(rwidth), int(rheight)))
img2 = cv2.cvtColor(img_src_copy, cv2.COLOR_BGR2RGB) # opencv读取的bgr格式图片转换成rgb格式
_image = QtGui.QImage(img2[:], img2.shape[1], img2.shape[0], img2.shape[1] * 3, QtGui.QImage.Format_RGB888)
jpg_out = QtGui.QPixmap(_image).scaled(rwidth, rheight) # 设置图片大小
self.label_7.setPixmap(jpg_out) # 设置图片显示
for i, lic_pred in enumerate(Lic_pred):
if i == 0:
print("i: ", i)
print("lic_pred[1]: ",lic_pred[1])
self.textEdit.setPlainText("车牌编号:"+lic_pred[1])
elif i == 1:
print("i: ", i)
self.textEdit.setPlainText("车牌编号:"+lic_pred[1])
elif i == 2:
print("i: ", i)
self.textEdit.setPlainText("车牌编号:"+lic_pred[1])
global plateNumber
plateNumber=lic_pred[1]
print("lic_pred[1]2: ", lic_pred[1])
import dbase
import sqlite3
import datetime
from datetime import datetime
conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
curr = conn.cursor()
curr.execute("select name from record_plate")
# curr.execute('insert into name_table values (null, ?)', [name])
results = curr.fetchall()
for i in results:
i = list(i)
print("i", i)
if i == [plateNumber]:
print("outTime: ", datetime.now())
curr.execute('update record_plate set record_time_out = "' + str(datetime.now().strftime("%Y%m%d %H:%M:%S")
) + '" where name="' + plateNumber + '"')
print("outTime2: ", datetime.now())
conn.commit()
conn.rollback()
if os.path.exists("platetemp.txt"):
os.remove("platetemp.txt")
if not os.path.exists("platetemp.txt"):
file2 = open('platetemp.txt', 'w')
file2.write(plateNumber)
file2.close()
conn.commit()
conn.rollback()
curr.close()
conn.close()
#得到当前数据库中在场车辆数量,更新出的车辆数量到数据库
conn = sqlite3.connect(databaseName, check_same_thread=False)
curr = conn.cursor()
curr.execute("select * from parking_spaces_number")
# curr.execute("select record_date from {}".format(tableName) )
results = curr.fetchall()
print("results", results[0])
name_list = []
for i in results:
i = list(i)
print(i)
print(i[4])
curr.execute('update parking_spaces_number set enter_qtty = "' + str(int(i[4])-1) + '"')
conn.commit()
curr.close()
conn.close()
else: # Lic_pred为空说明未能识别
print("无车牌发现")
def CostCalculation(self):
try:
self.carPlateRecogOut()
global plateNumber
print("plateNumber",plateNumber)
#判断是否是vip车辆
import dbase
import sqlite3
import datetime
from datetime import datetime
conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
curr = conn.cursor()
curr.execute("select * from vip")
# curr.execute("select record_date from {}".format(tableName) )
results = curr.fetchall()
# 数组包含某个文字判断
name_list = []
for i in results:
i = list(i)
print(i)
name_list += i
# name_list =','.join(i)
print("name_list2", name_list)
print("name_list type", type(name_list))
if plateNumber in name_list:
print("in vip namelist")
msg_box = QMessageBox(QMessageBox.Warning, '信息', 'vip车辆,门已打开,请出门')
msg_box.exec_()
conn.commit()
conn.rollback()
curr.close()
conn.close()
elif plateNumber not in name_list:
print("not in vip namelist")
conn.commit()
conn.rollback()
curr.close()
conn.close()
self.carPlateRecogOut()
self.currentNumberInit2()
print("停车费计算")
import dbase
import sqlite3
import datetime
print("")
conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
curr = conn.cursor()
curr.execute('select record_time from record_plate where name ="' + plateNumber + '"')
intime = curr.fetchall()
print("intime:", intime)
curr.execute('select record_time_out from record_plate where name ="' + plateNumber + '"')
outtime = curr.fetchall()
print("outtime:", outtime)
for i in intime: i = list(i); intime = ','.join(i)
for i in outtime: i = list(i); outtime = ','.join(i)
print("intime2:", intime)
print("outtime3:", outtime)
conn.commit()
curr.close()
conn.close()
#Fee = 0.001 # 每秒钟0.001元
Fee = float(self.lineEdit.text())
print("Fee",Fee)
date_time_obj_1 = datetime.datetime.strptime(intime, '%Y%m%d %H:%M:%S')
date_time_obj_2 = datetime.datetime.strptime(outtime, '%Y%m%d %H:%M:%S')
dt_time1 = pd.to_datetime(date_time_obj_1) # 转换日期时间到标准格式
dt_time2 = pd.to_datetime(date_time_obj_2) # 转换日期时间到标准格式
dateTimeInterval = dt_time2 - dt_time1 #得到日期时间差
print("dateTimeInterval", dateTimeInterval)
print("date_time_obj_1", date_time_obj_1)
print("date_time_obj_2", date_time_obj_2)
print("dt_time1", dt_time1)
print("dt_time2", dt_time2)
sec1 = time.mktime(dt_time1.timetuple()) # 转换为sec
sec2 = time.mktime(dt_time2.timetuple()) # 转换为sec
print("sec1", sec1)
print("sec2", sec2)
timeInterval = sec2 - sec1
print("timeInterval", timeInterval)
hourTimeInterval = round((timeInterval / 60 / 60),2) #妙转换小时
print("hourTimeInterval", hourTimeInterval)
Cost = timeInterval * Fee
print("Cost", Cost)
#self.textEdit_2.setPlainText("时长:" + str(timeInterval))
self.textEdit_2.setPlainText("时长:"+str(dateTimeInterval)+"小时 费用:"+str(Cost)+"元")
global costT
costT=str(Cost)
global timeIntervalT
timeIntervalT=timeInterval
#更新出场车牌停车费用到数据库
import dbase
import sqlite3
import datetime
from datetime import datetime
conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
curr = conn.cursor()
curr.execute('update record_plate set fee = "' + str(Cost) + '" where name="' + str(plateNumber) + '"')
conn.commit()
conn.rollback()
curr.close()
conn.close()
#打开二维码
self.open_third_ui()
#二维码打开付费后,更新数据库付费状态
import dbase
import sqlite3
import datetime
from datetime import datetime
conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
curr = conn.cursor()
curr.execute('update record_plate set fee_result= "' + ('Paid') + '" where name="' + str(plateNumber) + '"')
conn.commit()
conn.rollback()
curr.close()
conn.close()
msg_box = QMessageBox(QMessageBox.Warning, '信息', '门已打开,请出门')
msg_box.exec_()
if os.path.exists('pN.jpg'):
os.remove("pN.jpg")
#车出去后删除这个车的数据库记录
# import dbase
# import sqlite3
# conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
# cur = conn.cursor()
# curr.execute('delete from record_plate where name="' + plateNumber + '"') # 删除已经出去的车辆信息
# conn.commit()
# conn.rollback()
# cur.close()
# conn.close()
else:
print("incorrect plate")
except:
print("cost def mistake")
def manualOpen(self):
msg_box = QMessageBox(QMessageBox.Warning, '信息', '门已打开')
msg_box.exec_()
def open_second_ui(self):
self.second_ui = myRecord()
self.second_ui.show()
def open_third_ui(self):
self.third_ui = photoWin()
self.third_ui.show()
#记录显示****************************************************************************//
class myRecord(QtWidgets.QWidget, record.Ui_Frame):
def __init__(self):
super(myRecord, self).__init__()
self.setupUi(self)
self.resize(900, 500)
self.pushButton_6.clicked.connect(self.ExportAllData)
def checkDataView(self):
try:
import dbase
import sqlite3
conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
cur = conn.cursor()
cur.execute("select * from record_plate")
rows = cur.fetchall()
row = len(rows) # 取得记录个数,用于设置表格的行数
print("row",row)
vol = len(rows[0]) # 取得字段数,用于设置表格的列数
print("vol", vol)
cur.close()
conn.close()
self.tableWidget.setRowCount(row)
self.tableWidget.setColumnCount(vol)
for i in range(row):
for j in range(vol):
temp_data=rows[i][j] #临时记录,不能直接插入表格
data=QTableWidgetItem(str(temp_data)) #转换后可插入表格
if j != row:
data.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter) #居中显示
self.tableWidget.setItem(i,j,data)
self.tableWidget.verticalHeader().setVisible(False) #竖直序列号不可见
# 表头字体加粗
font = self.tableWidget.horizontalHeader().font()
font.setBold(True)
self.tableWidget.horizontalHeader().setFont(font)
except (ValueError, ArithmeticError):
print(" ")
except:
print(" ")
def ExportAllData(self):
import dbase
import sqlite3
conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
cur = conn.cursor()
cur.execute("select * from record_plate")
rows = cur.fetchall()
row = len(rows) # 取得记录个数,用于设置表格的行数
print("row",row)
vol = len(rows[0]) # 取得字段数,用于设置表格的列数
print("vol", vol)
cur.close()
conn.close()
print("导出记录")
if (os.path.isfile("ExportAllData.csv")):
os.remove("ExportAllData.csv")
with open('ExportAllData.csv', 'a') as file3:
file3.write("ID, 英文名, 日期时间, 中文名, 打卡记录, 编号;")
file3.close()
for i in range(row):
for j in range(vol):
temp_data=rows[i][j] #临时记录,不能直接插入表格
data2 = str(temp_data)
print("temp_data: ",temp_data)
with open('ExportAllData.csv', 'a') as file2:
if j==5:
file2.write(data2 + ", " + "\n")
file2.close()
else:
file2.write(data2)
file2.write(", ")
file2.close()
msg_box = QMessageBox(QMessageBox.Warning, '信息', '保存成功')
msg_box.exec_()
file5 = open("ExportAllData.csv", 'rt')
contents = file5.read() # 读取txt
data = contents.replace(";", ";\n") #找到特殊字符进行替换
fin = open('ExportAllData2.csv', "wt") #打开新的txt,上面替换的数据写到这里!
fin.write(data) #将处理好的结果再写进前面的txt内。
fin.close()
def deleteClicked(self):
button = self.sender()
try:
if button:
row = self.tableWidget.indexAt(button.pos()).row()
#row2 = self.tableWidget.selectedItems()[0].row() # 获取选中文本所在的行
#column = self.tableWidget.selectedItems()[0].column() # 获取选中文本所在的列
contents = self.tableWidget.selectedItems()[0].text() # 获取选中文本内容
print("contents",contents)
self.tableWidget.removeRow(row)
import dbase
import sqlite3
conn = sqlite3.connect("recordinfo.db", check_same_thread=False)
cur = conn.cursor()
print("contents", contents)
cur.execute('delete from record_plate where id = '+contents)
conn.commit()
conn.rollback()
cur.close()
conn.close()
self.checkDataView()
msg_box = QMessageBox(QMessageBox.Warning, '信息', '删除成功')
msg_box.exec_()
except (ValueError, ArithmeticError):
self.checkDataView()
msg_box = QMessageBox(QMessageBox.Warning, '信息', '请鼠标点击选择需要删除的序号,或未知异常')
msg_box.exec_()
except:
print(" ")
class photoWin(QtWidgets.QWidget, photoW.Ui_Frame):
def __init__(self):
super(photoWin, self).__init__()
self.setupUi(self)
self.resize(400, 500)
self.frame.setStyleSheet(open('style/style_frame.css').read())
self.textEdit.setPlainText("时长:" + str(timeIntervalT) + " 费用:" + costT)
#封装pyqtSignal信号
class Communicate(QObject):
signal=pyqtSignal(str)
class VideoTimer(QThread):
def __init__(self):
QThread.__init__(self)
self.timeSignal=Communicate()
self.mutex = QMutex()
print("tttt5")
def run(self):
with QMutexLocker(self.mutex):
self.stopped = False
while True:
if self.stopped == True:
return
#发送信号给视频要求更新,emit发送信号
print("ttttrun")
self.timeSignal.signal.emit("1")
#时间延迟
time.sleep(0.8)
def stop(self):
with QMutexLocker(self.mutex):
self.stopped = True
if __name__=="__main__":
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
app=QtWidgets.QApplication(sys.argv)
# 设置登录窗口
login_ui = LoginDialog()
register_ui = RegisterDialog()
# 校验是否验证通过
while login_ui.exec_() == QDialog.Accepted:
if login_ui.isRisterButtonClicked==True:
login_ui.registerdlg=RegisterDialog()
if login_ui.registerdlg.exec_()==QDialog.Accepted:
if login_ui.registerdlg.isLoginButtonClicked ==True:
continue
else:
Widget = myWin()
Widget.showMaximized();
Widget.show()
sys.exit(app.exec_())
Widget=myWin()
Widget.showMaximized();
Widget.show()
sys.exit(app.exec_())
3. 运行结果
三、在线协助:
如需安装运行环境或远程调试,见文章底部个人 QQ 名片,由专业技术人员远程协助!
1)远程安装运行环境,代码调试
2)Qt, C++, Python入门指导
3)界面美化
4)软件制作
博主推荐文章:python人脸识别统计人数qt窗体-CSDN博客
博主推荐文章:Python Yolov5火焰烟雾识别源码分享-CSDN博客
Python OpenCV识别行人入口进出人数统计_python识别人数-CSDN博客
个人博客主页:alicema1111的博客_CSDN博客-Python,C++,网页领域博主
博主所有文章点这里:alicema1111的博客_CSDN博客-Python,C++,网页领域博主