PyQt5-小总结

发布时间:2024年01月09日

之前学习PyQt5,然后那段时间想做一个桌面小程序,后来由于学习内容较多就做了一小部分,但是可以进行页面跳转。大家如果是初学者对Python感兴趣而且刚学数据库时可以看看代码,可能会有点启发。

效果:

?登录进来是这:

?

?实现了账号密码的增删改功能

结构很简单

源代码如下:

database.py

import pymysql # 导入操作MySQL数据库的模块

userName="" # 记录用户名

# 打开数据库连接
def open():
    db = pymysql.connect(host="localhost", user="root", passwd="123456", database="db_goods",charset="utf8")
    return db # 返回连接对象

#数据库增删改
def exec(sql,values):
    db=open() # 连接数据库
    cursor = db.cursor() # 使用cursor()方法获取操作游标
    try:
        cursor.execute(sql,values) # 执行增删改的SQL语句
        db.commit() # 提交数据
        return 1 # 执行成功
    except:
        db.rollback() # 发生错误时回滚
        return 0 # 执行失败
    finally:
        cursor.close() # 关闭游标
        db.close() # 关闭数据库连接
# 带参数的精确查询
def query(sql,*keys):
    db=open() # 连接数据库
    cursor = db.cursor() # 使用cursor()方法获取操作游标
    cursor.execute(sql,keys) # 执行查询SQL语句
    result = cursor.fetchall() # 记录查询结果
    cursor.close() # 关闭游标
    db.close() # 关闭数据库连接
    return result # 返回查询结果
# 不带参数的模糊查询
def query2(sql):
    db=open() # 连接数据库
    cursor = db.cursor() # 使用cursor()方法获取操作游标
    cursor.execute(sql) # 执行查询SQL语句
    result = cursor.fetchall() # 记录查询结果
    cursor.close() # 关闭游标
    db.close() # 关闭数据库连接
    return result # 返回查询结果

图片要放在这种文件里

<RCC>
  <qresource prefix="newPrefix">
    <file>images/loginPIC.jpg</file>
    <file>images/main.jpg</file>
  </qresource>
</RCC>

?需要用到这个工具,大家自己查一下,很容易配置

login.py

#login.py
from PyQt5 import QtCore, QtGui, QtWidgets
import dataBase
from PyQt5.QtWidgets import QMessageBox
import main
from PyQt5.QtWidgets import *

class Ui_MainWindow(object):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowFlags(QtCore.Qt.MSWindowsFixedSizeDialogHint)
        MainWindow.resize(485, 280)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 261, 281))
        self.label.setPixmap(QtGui.QPixmap(":/newPrefix/images/loginPIC.jpg"))
        self.label.setObjectName("label")

        self.label_user = QtWidgets.QLabel(self.centralwidget)
        self.label_user.setGeometry(QtCore.QRect(270, 70, 72, 41))
        self.label_user.setObjectName("label_2")

        self.label_pwd = QtWidgets.QLabel(self.centralwidget)
        self.label_pwd.setGeometry(QtCore.QRect(270, 130, 72, 21))
        self.label_pwd.setObjectName("label_3")

        self.lineEdit_userName = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_userName.setGeometry(QtCore.QRect(330, 80, 113, 21))
        self.lineEdit_userName.setObjectName("lineEdit")

        self.lineEdit_userPasswd = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_userPasswd.setGeometry(QtCore.QRect(330, 130, 113, 21))
        self.lineEdit_userPasswd.setObjectName("lineEdit_2")
        self.lineEdit_userPasswd.setEchoMode(QtWidgets.QLineEdit.Password)

        self.pushButton_login = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_login.setGeometry(QtCore.QRect(290, 190, 61, 28))
        self.pushButton_login.setObjectName("pushButton")

        self.pushButton_exit = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_exit.setGeometry(QtCore.QRect(370, 190, 61, 28))
        self.pushButton_exit.setObjectName("pushButton_2")

        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.pushButton_exit.clicked.connect(MainWindow.close)  # 关闭登录窗体
        self.pushButton_login.clicked.connect(self.openMain)   #登录

    def openMain(self):
        dataBase.userName = self.lineEdit_userName.text()
        userPasswd = self.lineEdit_userPasswd.text()

        if dataBase.userName and userPasswd:
            result = dataBase.query("select * from goods_user where userName = %s and userPasswd = %s", dataBase.userName, userPasswd)
            if len(result) > 0:
                self.main_window = QtWidgets.QMainWindow()
                self.main_ui = main.Ui_MainWindow()
                self.main_ui.setupUi(self.main_window)
                self.main_window.show()
                MainWindow.hide()
            else:
                self.lineEdit_userName.setText("")
                self.lineEdit_userPasswd.setText("")
                QMessageBox.warning(None, '警告', '请输入正确的用户名和密码!', QMessageBox.Ok)
        else:
            QMessageBox.warning(None, '警告', '请输入用户名和密码!', QMessageBox.Ok)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "二手商品信息管理平台登录"))
        self.label_user.setText(_translate("MainWindow", "用户名:"))
        self.label_pwd.setText(_translate("MainWindow", "密  码:"))
        self.pushButton_login.setText(_translate("MainWindow", "登录"))
        self.pushButton_exit.setText(_translate("MainWindow", "退出"))

import img_rc
import sys

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

main.py

#login.py
from PyQt5 import QtCore, QtGui, QtWidgets
import dataBase
from PyQt5.QtWidgets import QMessageBox
import main
from PyQt5.QtWidgets import *

class Ui_MainWindow(object):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowFlags(QtCore.Qt.MSWindowsFixedSizeDialogHint)
        MainWindow.resize(485, 280)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 261, 281))
        self.label.setPixmap(QtGui.QPixmap(":/newPrefix/images/loginPIC.jpg"))
        self.label.setObjectName("label")

        self.label_user = QtWidgets.QLabel(self.centralwidget)
        self.label_user.setGeometry(QtCore.QRect(270, 70, 72, 41))
        self.label_user.setObjectName("label_2")

        self.label_pwd = QtWidgets.QLabel(self.centralwidget)
        self.label_pwd.setGeometry(QtCore.QRect(270, 130, 72, 21))
        self.label_pwd.setObjectName("label_3")

        self.lineEdit_userName = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_userName.setGeometry(QtCore.QRect(330, 80, 113, 21))
        self.lineEdit_userName.setObjectName("lineEdit")

        self.lineEdit_userPasswd = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_userPasswd.setGeometry(QtCore.QRect(330, 130, 113, 21))
        self.lineEdit_userPasswd.setObjectName("lineEdit_2")
        self.lineEdit_userPasswd.setEchoMode(QtWidgets.QLineEdit.Password)

        self.pushButton_login = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_login.setGeometry(QtCore.QRect(290, 190, 61, 28))
        self.pushButton_login.setObjectName("pushButton")

        self.pushButton_exit = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_exit.setGeometry(QtCore.QRect(370, 190, 61, 28))
        self.pushButton_exit.setObjectName("pushButton_2")

        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.pushButton_exit.clicked.connect(MainWindow.close)  # 关闭登录窗体
        self.pushButton_login.clicked.connect(self.openMain)   #登录

    def openMain(self):
        dataBase.userName = self.lineEdit_userName.text()
        userPasswd = self.lineEdit_userPasswd.text()

        if dataBase.userName and userPasswd:
            result = dataBase.query("select * from goods_user where userName = %s and userPasswd = %s", dataBase.userName, userPasswd)
            if len(result) > 0:
                self.main_window = QtWidgets.QMainWindow()
                self.main_ui = main.Ui_MainWindow()
                self.main_ui.setupUi(self.main_window)
                self.main_window.show()
                MainWindow.hide()
            else:
                self.lineEdit_userName.setText("")
                self.lineEdit_userPasswd.setText("")
                QMessageBox.warning(None, '警告', '请输入正确的用户名和密码!', QMessageBox.Ok)
        else:
            QMessageBox.warning(None, '警告', '请输入用户名和密码!', QMessageBox.Ok)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "二手商品信息管理平台登录"))
        self.label_user.setText(_translate("MainWindow", "用户名:"))
        self.label_pwd.setText(_translate("MainWindow", "密  码:"))
        self.pushButton_login.setText(_translate("MainWindow", "登录"))
        self.pushButton_exit.setText(_translate("MainWindow", "退出"))

import img_rc
import sys

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

user.py

#user.py
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox, QTableWidgetItem, QMainWindow

import dataBase

class Ui_MainWindow(QMainWindow):

    # 构造方法
    def __init__(self):
        super(Ui_MainWindow, self).__init__()
        self.setWindowFlags(QtCore.Qt.MSWindowsFixedSizeDialogHint)  # 只显示最小化和关闭按钮
        self.setupUi(self) # 初始化窗体设置

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(546, 423)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tableinfo = QtWidgets.QTableWidget(self.centralwidget)
        self.tableinfo.setGeometry(QtCore.QRect(0, 0, 400, 420))
        self.tableinfo.setObjectName("tableWidget")
        self.tableinfo.setColumnCount(2)
        self.tableinfo.setRowCount(0)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        self.tableinfo.setHorizontalHeaderItem(0, item)
        item = QtWidgets.QTableWidgetItem()
        item.setTextAlignment(QtCore.Qt.AlignCenter)
        self.tableinfo.setHorizontalHeaderItem(1, item)
        self.tableinfo.setColumnWidth(0, 195)# 调整第一列(索引0)的宽度到特定宽度
        self.tableinfo.setColumnWidth(1, 195)# 调整第二列(索引1)的宽度到特定宽度
        self.tableinfo.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
        #表格列将根据窗口大小自动调整宽度,以填充整个表格而不会出现水平滚动条。
        self.pushButton_add = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_add.setGeometry(QtCore.QRect(440, 180, 61, 31))
        self.pushButton_add.setObjectName("pushButton")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(400, 110, 61, 21))
        self.label.setObjectName("label")
        self.lineEdit_userName = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_userName.setGeometry(QtCore.QRect(460, 110, 71, 21))
        self.lineEdit_userName.setObjectName("lineEdit")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(410, 140, 51, 20))
        self.label_2.setObjectName("label_2")
        self.lineEdit_passwd = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_passwd.setGeometry(QtCore.QRect(460, 140, 71, 21))
        self.lineEdit_passwd.setObjectName("lineEdit_2")
        self.pushButton_edit = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_edit.setGeometry(QtCore.QRect(440, 230, 61, 31))
        self.pushButton_edit.setObjectName("pushButton_2")
        self.pushButton_del = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_del.setGeometry(QtCore.QRect(440, 270, 61, 31))
        self.pushButton_del.setObjectName("pushButton_3")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.tableinfo.setAlternatingRowColors(True)  # 使表格颜色交错显示
        self.tableinfo.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.query() # 窗体加载时显示所有数据
        self.tableinfo.itemClicked.connect(self.getItem) # 获取选中的单元格数据
        self.pushButton_add.clicked.connect(self.add)
        self.pushButton_edit.clicked.connect(self.edit) # 绑定修改按钮的单击信号
        self.pushButton_del.clicked.connect(self.delete) # 绑定删除按钮的单击信号

    def query(self):
        self.tableinfo.setRowCount(0) # 清空表格中的所有行
        result = dataBase.query("select * from goods_user") # 调用服务类中的公共方法执行查询语句
        row = len(result)  # 取得记录个数,用于设置表格的行数
        self.tableinfo.setRowCount(row)  # 设置表格行数
        self.tableinfo.setColumnCount(2)  # 设置表格列数
        for i in range(row):  # 遍历行
            for j in range(self.tableinfo.columnCount()):  # 遍历列
                data = QTableWidgetItem(str(result[i][j]))  # 转换后可插入表格
                data.setFlags(data.flags() & ~QtCore.Qt.ItemIsEditable)  # 设置单元格为只读
                self.tableinfo.setItem(i, j, data) # 设置每个单元格的数据

    def getItem(self, item):
        if item.column() == 0:  # 如果点击的是第一列
            self.select1 = item.text()  # 获取点击单元格的文本
            row = item.row()  # 获取点击单元格所在的行
            item2 = self.tableinfo.item(row, 1)  # 获取同一行第二列的项
            if item2 is not None:
                self.select2 = item2.text()
                self.lineEdit_userName.setText(self.select1)  # 显示在用户名文本框中
                self.lineEdit_passwd.setText(self.select2)  # 显示在密码文本框中

        if item.column() == 1:
            self.select2 = item.text()
            row = item.row()
            item1 = self.tableinfo.item(row, 0)
            if item1 is not None:
                self.select1 = item1.text()
                self.lineEdit_userName.setText(self.select1)
                self.lineEdit_passwd.setText(self.select2)
    def add(self):
        userName = self.lineEdit_userName.text() # 记录输入的用户名
        userPwd = self.lineEdit_passwd.text() # 记录输入的用户密码
        if userName != "" and userPwd != "": # 判断用户名和密码不为空
            # 执行添加语句
            result=dataBase.exec("insert into goods_user(userName,userPasswd) values (%s,%s)",(userName,userPwd))
            if result>0:  # 如果结果大于0,说明添加成功
                self.query() # 在表格中显示最新数据
                QMessageBox.information(None, '提示', '信息添加成功!', QMessageBox.Ok)
        else:
            QMessageBox.warning(None, '警告', '请输入数据后,再执行相关操作!', QMessageBox.Ok)

    def edit(self):
        try:
            if self.select1!="": # 判断是否选择了要修改的数据
                userPwd = self.lineEdit_passwd.text() # 记录修改的用户密码
                if userPwd != "": # 判断密码不为空
                    # 执行修改操作
                    result=dataBase.exec("update goods_user set userPasswd= %s where userName=%s",(userPwd,self.select1))
                    if result>0: # 如果结果大于0,说明修改成功
                        self.query() # 在表格中显示最新数据
                        QMessageBox.information(None, '提示', '信息修改成功!', QMessageBox.Ok)
        except:
            QMessageBox.warning(None, '警告', '请先选择要修改的数据!', QMessageBox.Ok)

    def delete(self):
        try:
            if self.select1!="": # 判断是否选择了要删除的数据
                # 执行删除操作
                result=dataBase.exec("delete from goods_user where userName= %s",(self.select1,))
                if result>0: # 如果结果大于0,说明删除成功
                    self.query() # 在表格中显示最新数据
                    QMessageBox.information(None, '提示', '信息删除成功!', QMessageBox.Ok)
        except:
            QMessageBox.warning(None, '警告', '请先选择要删除的数据!', QMessageBox.Ok)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "账号密码设置"))
        item = self.tableinfo.horizontalHeaderItem(0)
        item.setText(_translate("MainWindow", "用户名"))
        item = self.tableinfo.horizontalHeaderItem(1)
        item.setText(_translate("MainWindow", "密码"))
        self.pushButton_add.setText(_translate("MainWindow", "添加"))
        self.label.setText(_translate("MainWindow", " 用 户:"))
        self.label_2.setText(_translate("MainWindow", "密 码:"))
        self.pushButton_edit.setText(_translate("MainWindow", "修改"))
        self.pushButton_del.setText(_translate("MainWindow", "删除"))


文章来源:https://blog.csdn.net/m0_64335844/article/details/135484240
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。