PyQt5 快速开发 - 学生管理系统项目实战报告

PyQt5 快速开发 - 学生管理系统项目实战报告

  • 一、登陆界面搭建
  • 二、登陆验证
  • 三、主界面
    • 1、初始化
    • 2、添加控件
    • 3、设置函数与信号
    • 4、树的函数
    • 5、右键选项信号槽
    • 6、数据表显示函数
    • 7、运行代码按钮信号槽
    • 8、代码输入框
    • 9、清空按钮与富文本浏览器
  • 四、新建数据表对话框
    • 1、添加控件
    • 2、初始化对话框
    • 3、设置控件属性
    • 4、确定按钮信号槽
    • 5、连接 UI 窗体
  • 五、删除记录对话框
  • 六、全部代码

        为了实现我的计划,我使用 PyQt5 编写程序,制作了一个简易 GUI 的 学生管理系统,作为 2021 年最后一个程序,运用到了我在2021年所学的大部分知识,绝对算得上是压轴程序,但是并没有给界面做美化。

  • 登录界面
    PyQt5 快速开发 - 学生管理系统项目实战报告_第1张图片
  • 主界面
    PyQt5 快速开发 - 学生管理系统项目实战报告_第2张图片

一、登陆界面搭建

        登录界面用的 Designer 可视化程序搭建的,动动鼠标就能轻松搭建出一个用户界面。
PyQt5 快速开发 - 学生管理系统项目实战报告_第3张图片
然后在 Pycharm 中用 PyUIC 把 .ui 文件转为 .py 文件。

二、登陆验证

在界面程序中给两个按钮(登录 和 退出)绑定信号

# 退出
self.retranslateUi(widget)
self.pushButton_2.clicked.connect(widget.close)  # type: ignore

# 登录
self.pushButton.clicked.connect(self.login_in)  # type: ignore
self.pushButton.setShortcut('Return')

写登录信号槽

# 验证登录
def login_in(self):
	# 全局变量传参给其他所有界面
    global gl_db
    global gl_host
    global gl_pwd
    global gl_user
    global gl_port

    gl_db = self.lineEdit_5.text()
    gl_host = self.lineEdit_3.text()
    gl_pwd = self.lineEdit_2.text()
    gl_user = self.lineEdit.text()
    try:
        port = int(self.lineEdit_4.text())
        try:
            conn = pymysql.connect(host=gl_host, port=gl_port, db=gl_db, user=gl_user, password=gl_pwd)
            print('登录数据库{}成功'.format(gl_db))
            self.messageDialog('提示', '登录数据库{}成功'.format(gl_db))
            conn.close()
            del conn
            # 登录成功后跳转到主界面
            self.main_show = Fulling()
            self.main_show.show()
            mainWindow.close()
        except pymysql.err.OperationalError:
            print('由于目标计算机积极拒绝,无法连接。')
            self.messageDialog('警告', '由于目标计算机积极拒绝,无法连接。')
    except ValueError:
        print('端口号错误')
        self.messageDialog('警告', '端口号错误')
    except Exception as err:
        print('错误:', err)
        self.messageDialog('警告', str(err))

# 提示信息
def messageDialog(self, title, text):
    msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, title, text)
    msg_box.exec_()

登录逻辑程序代码

class Login(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setFixedSize(600, 400)  # 禁止拖动
        self.setWindowIcon(QtGui.QIcon('./img/001.ico'))  # 设置窗体标题图标
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)  # 禁用最大化

        # 背景图片
        image = QtGui.QPixmap()
        image.load(r'./img/login_bg.jpg')
        bg = QtGui.QPalette()
        bg.setBrush(self.backgroundRole(), QtGui.QBrush(image))
        self.setPalette(bg)
        self.setAutoFillBackground(True)


if __name__ == '__main__':
    gl_db = ''
    gl_host = ''
    gl_pwd = ''
    gl_user = ''
    gl_port = 0
    # 创建 QApplication 类的实例
    logapp = QApplication(sys.argv)
    # 创建窗体
    mainWindow = Login()
    # 关联login
    ui = Ui_widget()
    ui.setupUi(mainWindow)
    # 打开窗体
    mainWindow.show()
    # 退出窗体
    sys.exit(logapp.exec_())

PyQt5 快速开发 - 学生管理系统项目实战报告_第4张图片

三、主界面

因为主界面涉及到的控件比较复杂,所以直接用代码写出来,不使用 Designer。

1、初始化

  • 先给界面初始化,标题,窗口大小,图标,控件,并且连接数据库
class Fulling(QWidget):
	# 初始化
    def __init__(self):
        super().__init__()
        # 窗口标题
        self.setWindowTitle('学生管理系统')
        # 窗口大小
        self.resize(720, 600)
        # 窗口居中
        self.center()
        # 图标
        self.setWindowIcon(QIcon('./img/001.ico'))
        # 连接数据库
        self.conn = pymysql.connect(host=gl_host, port=gl_port, user=gl_user, password=gl_pwd, db=gl_db)
        self.tree_view = None
        self.table_view = None
        self.queryModel = None
        self.text_edit = None
        self.run_button = None
        self.row = None
        self.vol = None
        self.text_browser = None
        self.clear_button = None
        self.add_db_view = None
        self.del_db_view = None
        self.cur = self.conn.cursor()
        self.init_ui()

	# 窗口居中
    def center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move(round((screen.width() - size.width()) / 2), round((screen.height() - size.height()) / 2))

	# 警告信息
    @staticmethod
    def message_dialog(title, text):
        msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, title, text)
        msg_box.exec_()

2、添加控件

  • 窗口添加控件,并为他们布局
	# 窗口布局
	def create_window(self):
	    # 设置树属性
	    self.tree_view = QTreeWidget()
	    # 设置表格属性
	    self.table_view = QTableWidget()
	    # 设置文本框
	    self.text_edit = QTextEdit()
	    # 设置运行按钮
	    self.run_button = QPushButton('运行所有代码')
	    # 设置清空按钮
	    self.clear_button = QPushButton('清空代码')
	    # 设置查看文本
	    self.text_browser = QTextBrowser()
	    # 表格宽度自适应
	    self.table_view.horizontalHeader().setStretchLastSection(True)
	    self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
	
	    # 左侧布局
	    left_layout = QVBoxLayout()
	    left_layout.addWidget(self.tree_view, 15)
	    left_layout.addWidget(self.text_browser, 9)
	
	    # 右中
	    mid_layout = QHBoxLayout()
	    mid_layout.addWidget(self.run_button)
	    mid_layout.addWidget(self.clear_button)
	    mid_layout.addWidget(QSplitter())
	
	    # 右侧布局
	    right_layout = QVBoxLayout()
	    right_layout.addWidget(self.table_view, 15)
	    right_layout.addLayout(mid_layout, 1)
	    right_layout.addWidget(self.text_edit, 8)
	
	    # 创建界面
	    layout = QHBoxLayout(self)
	    layout.addLayout(left_layout, 1)
	    layout.addLayout(right_layout, 3)
	    self.setLayout(layout)

3、设置函数与信号

  • 给每个控件添加自己的函数和信号
	# 设置窗口主要部件和信号
	def init_ui(self):
	    # 创建窗口
	    self.create_window()
	    # 设置树
	    self.set_tree_view()
	    # 设置表格
	    self.set_table_view()
	    # 设置文本框
	    self.set_text_edit()
	    # 创建运行按钮
	    self.set_run_button()
	    # 创建清空按钮
	    self.set_clear_button()
	    # 创建查看文本
	    self.set_text_browser()
	
	    # 信号槽
	    self.tree_view.clicked.connect(self.on_tree_clicked)
	    self.run_button.clicked.connect(self.run_program)
	    self.clear_button.clicked.connect(self.clear_all)
	
	    # 给树添加右键
	    self.tree_view.setContextMenuPolicy(Qt.CustomContextMenu)
	    self.tree_view.customContextMenuRequested.connect(self.right_menu_show)
	
	    # 运行按钮快捷键
	    self.run_button.setShortcut('F5')

4、树的函数

  • 让树能够显示所有的数据表
  • 本来想的是把所有的数据表、视图、事件等都显示出来,但是这里我只写了显示数据表
    # 树
    def set_tree_view(self):
        # 树行数
        self.tree_view.setColumnCount(1)
        # 树标题
        self.tree_view.setHeaderLabel(gl_db + '.db')
        # 设置根节点
        root = QtWidgets.QTreeWidgetItem(self.tree_view)
        root.setText(0, '表')  # 只有一列
        root.setIcon(0, QIcon('img/db_logo.png'))
        # 创建游标
        cursor = self.conn.cursor()
        cursor.execute("show tables;")
        res = cursor.fetchall()
        # 遍历表
        for i in range(len(res)):
            child = QtWidgets.QTreeWidgetItem(root)  # 指定父目录
            child.setText(0, res[i][0])
            child.setText(1, '{}'.format(i + 1))
            child.setIcon(0, QIcon('img/table_logo.png'))
        # 树默认收缩
        root.setExpanded(False)
        # 树根节点
        self.tree_view.addTopLevelItem(root)
  • 树中左键单击展开树 或 打开数据表
    PyQt5 快速开发 - 学生管理系统项目实战报告_第5张图片
    # 树左键单击
    def on_tree_clicked(self):
        try:
        	# 获取树中的内容
            item = self.tree_view.currentItem()
            # 如果单击的是根目录则展开或收缩树
            if item.text(0) == '表':
                print('左键单击{}'.format(item.text(0)))
                if self.tree_view.currentItem().isExpanded():
                    self.tree_view.collapseAll()
                else:
                    self.tree_view.expandAll()
                    
            # 如果单击的是表则打开表
            else:
                item = self.tree_view.currentItem()
                self.cur.execute('select * from ' + item.text(0))
                self.select_run()
                print('左键单击{}'.format(item.text(0)))
        except Exception as e:
            print('树左键单击{}'.format(e))
            self.message_dialog('提示', '请先输入数据')
  • 树中右键单击显示 右键菜单选项
    PyQt5 快速开发 - 学生管理系统项目实战报告_第6张图片
    # 树右键单击
    def right_menu_show(self):
        try:
            item = self.tree_view.currentItem()
            if item.text(0) == '表':
                print('右键单击{}'.format(item.text(0)))
                # 添加菜单选项
                self.contextMenu = QMenu()
                self.add_db = self.contextMenu.addAction(u'新建数据表')
                self.flash_db = self.contextMenu.addAction(u'刷新')
                self.close_db = self.contextMenu.addAction(u'退出')
                self.contextMenu.popup(QCursor.pos())
                # 给菜单选项绑定信号
                self.add_db.triggered.connect(self.add_database)  # type:ignore
                self.flash_db.triggered.connect(self.flash)  # type:ignore
                self.close_db.triggered.connect(self.close_database)  # type:ignore
                self.contextMenu.show()

            else:
                # 数据表的右键
                print('右键单击{},序号是{}'.format(item.text(0), item.text(1)))
                self.contextMenu = QMenu()
                self.open = self.contextMenu.addAction(u'打开表')
                self.drop = self.contextMenu.addAction(u'删除表')
                self.add = self.contextMenu.addAction(u'添加记录')
                self.delete = self.contextMenu.addAction(u'删除记录')
                self.update = self.contextMenu.addAction(u'更改记录')
                self.select = self.contextMenu.addAction(u'查询记录')
                self.open.triggered.connect(self.open_table)  # type:ignore
                self.drop.triggered.connect(self.drop_table)  # type:ignore
                self.add.triggered.connect(self.add_table)  # type:ignore
                self.delete.triggered.connect(self.delete_table)  # type:ignore
                self.update.triggered.connect(self.update_table)  # type:ignore
                self.select.triggered.connect(self.select_table)  # type:ignore
                self.contextMenu.popup(QCursor.pos())
                self.contextMenu.show()

        except Exception as e:
            print(e)

5、右键选项信号槽

  • 根目录的右键菜单
    PyQt5 快速开发 - 学生管理系统项目实战报告_第7张图片
    # 树刷新
    def flash(self):
        """添加数据表后的刷新操作"""
        print('刷新')
        item = self.tree_view.currentItem()
        root = QtWidgets.QTreeWidgetItem(self.tree_view)
        root.setText(0, '表')  # 只有一列
        root.setIcon(0, QIcon('img/db_logo.png'))
        cursor = self.conn.cursor()
        cursor.execute("show tables;")
        res = cursor.fetchall()

        # 清除树
        curr_node = self.tree_view.currentItem()
        root_index = self.tree_view.indexOfTopLevelItem(curr_node)
        self.tree_view.takeTopLevelItem(root_index)

		# 再把刷新获取的树放上去
        for i in range(len(res)):
            child = QtWidgets.QTreeWidgetItem(root)  # 指定父目录
            child.setText(0, res[i][0])
            child.setText(1, '{}'.format(i + 1))
            child.setIcon(0, QIcon('img/table_logo.png'))

    # 新建数据表 这里要用另外的窗口作为对话框,在第四点
    def add_database(self):
        try:
        	# 打开对话框
            self.add_db_view = AdDB()
            add_ui = Ui_add_db_object()
            add_ui.setupUi(self.add_db_view)
            self.add_db_view.show()
        except Exception as e:
            print(e)

        print('新建数据表')

    # 退出数据表
    def close_database(self):
        reply = QMessageBox.question(self, '退出', '确定退出', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        if reply == QMessageBox.Yes:
            sender = self.sender()
            main_app_db = QApplication.instance()
            main_app_db.quit()
        print('退出数据表')
  • 数据表的右键菜单,下面四个操作没有写完,因为需要新建一个对话框
    PyQt5 快速开发 - 学生管理系统项目实战报告_第8张图片
    # 右键打开
    def open_table(self):
        item = self.tree_view.currentItem()
        self.cur.execute('select * from ' + item.text(0))
        self.select_run()
        print('打开 {}'.format(item.text(0)))

    # 右键删除表
    def drop_table(self):
        item = self.tree_view.currentItem()
        reply = QMessageBox.question(self, '删除表', '确定要删除吗?', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        if reply == QMessageBox.Yes:
            self.cur.execute('drop table ' + item.text(0))
            self.text_browser.append('删除表 {} 成功,右击根目录刷新'.format(item.text(0)))
        print('删除 {}'.format(item.text(0)))

    # TODO 添加记录
    def add_table(self):
        self.message_dialog('提示', '功能还没开发')
        print('添加记录')

    # TODO 删除记录
    def delete_table(self):
        try:
            self.del_db_view = DelDB()
            del_ui = Ui_delete_win()
            del_ui.setupUi(self.del_db_view)
            self.del_db_view.show()
        except Exception as e:
            print(e)
        print('删除记录')

    # TODO 更改记录
    def update_table(self):
        self.message_dialog('提示', '功能还没开发')
        print('更改记录')

    # TODO 查询记录
    def select_table(self):
        self.message_dialog('提示', '功能还没开发')
        print('查询记录')

6、数据表显示函数

PyQt5 快速开发 - 学生管理系统项目实战报告_第9张图片

  • 定义表格控件是用来显示数据表的
    # 表格控件
    def set_table_view(self):
        self.cur.execute('show tables')
        db_len = self.cur.fetchone()
        self.cur.execute('select * from ' + db_len[0])  # 将数据从数据库中拿出来
        self.select_run()
  • 让所选表的数据显示在表格控件里

这里的代码参考的是 PyQt实现读取MySql数据库表数据将其显示在TableWidget并保存为excel表格

    # 表格填充内容
    def table_data(self, i, j, data):
        item = QtWidgets.QTableWidgetItem()
        self.table_view.setItem(i, j, item)
        item = self.table_view.item(i, j)
        item.setText(str(data))

    # 运行查询
    def select_run(self):
        try:
            total = self.cur.fetchall()
            col_result = self.cur.description
            self.row = self.cur.rowcount  # 取得记录个数,用于设置表格的行数
            if self.row == 0:
                self.text_browser.moveCursor(QTextCursor.End)
                self.text_browser.append('数据表中没有任何记录')
            else:
                self.vol = len(total[0])  # 取得字段数,用于设置表格的列数
                col_result = list(col_result)
                a = 0
                self.table_view.setColumnCount(self.vol)
                self.table_view.setRowCount(self.row)
                for i in col_result:  # 设置表头信息,将mysql数据表中的表头信息拿出来,放进TableWidget中
                    item = QtWidgets.QTableWidgetItem()
                    self.table_view.setHorizontalHeaderItem(a, item)
                    item = self.table_view.horizontalHeaderItem(a)
                    item.setText(i[0])
                    a = a + 1

                total = list(total)  # 将数据格式改为列表形式,其是将数据库中取出的数据整体改为列表形式
                for i in range(len(total)):  # 将相关的数据
                    total[i] = list(total[i])  # 将获取的数据转为列表形式
                for i in range(self.row):
                    for j in range(self.vol):
                        self.table_data(i, j, total[i][j])
        except Exception as e:
            print(e)

7、运行代码按钮信号槽

PyQt5 快速开发 - 学生管理系统项目实战报告_第10张图片

  • 运行代码按钮需要识别文本框内输入的操作是增、删、改、查、创建数据表中的哪一个
	# 运行按钮
    def run_program(self):
        try:
            # 获取填写的代码
            text = self.text_edit.toPlainText()
            # 删掉所有的换行
            text = text.replace('\n', '')
            # 所有代码大写
            text = text.upper()
            # 不同代码分片
            texts = text.split(';')
            for i in range(len(texts)):
                try:
                    if texts[i][:6] == 'SELECT':
                        print('执行查询{}'.format(texts[i]))
                        self.cur.execute(texts[i])  # 将数据从数据库中拿出来
                        self.select_run()
                        self.text_browser.moveCursor(QTextCursor.End)
                        self.text_browser.append('查询{}'.format(texts[i]))
                        self.row_ref()
                    elif texts[i][:6] == 'UPDATE':
                        print('执行更新{}'.format(texts[i]))
                        self.cur.execute(texts[i])  # 将数据从数据库中拿出来
                        self.text_browser.moveCursor(QTextCursor.End)
                        self.text_browser.append('更新{}'.format(texts[i]))
                        self.row_ref()
                    elif texts[i][:6] == 'INSERT':
                        print('执行插入{}'.format(texts[i]))
                        self.cur.execute(texts[i])  # 将数据从数据库中拿出来
                        self.text_browser.moveCursor(QTextCursor.End)
                        self.text_browser.append('插入{}'.format(texts[i]))
                        self.row_ref()
                    elif texts[i][:6] == 'DELETE':
                        print('执行删除{}'.format(texts[i]))
                        self.cur.execute(texts[i])  # 将数据从数据库中拿出来
                        self.text_browser.moveCursor(QTextCursor.End)
                        self.text_browser.append('删除{}'.format(texts[i]))
                        self.row_ref()
                    elif texts[i][:6] == 'CREATE' and texts[i].find('TABLE') != -1:
                        print('创建数据表')
                        self.cur.execute(texts[i])  # 将数据从数据库中拿出来
                        self.text_browser.moveCursor(QTextCursor.End)
                        self.text_browser.append('创建数据表{}'.format(texts[i]))
                        self.flash()
                except Exception as e:
                    if '1096' in str(e):
                        print('没有使用数据库')
                        self.message_dialog('没有使用数据库', str(e))
                    elif '1054' in str(e):
                        print('没有这个数据库')
                        self.message_dialog('没有这个数据库', str(e))
                    elif '1064' in str(e):
                        print('语法错误')
                        self.message_dialog('语法错误', str(e))
                    else:
                        print('rr', e)
                        self.message_dialog('其他错误', str(e))
            print('run', text)
        except Exception as e:
            print('e:', e)
  • 执行 SQL 语句之后,查看影响行,把结果打印在富文本浏览器中
    PyQt5 快速开发 - 学生管理系统项目实战报告_第11张图片
    PyQt5 快速开发 - 学生管理系统项目实战报告_第12张图片
	# 查看受影响行
    def row_ref(self):
        cur_count = self.cur.rowcount
        if cur_count > 0:
            self.conn.commit()
            self.text_browser.moveCursor(QTextCursor.End)
            self.text_browser.append('执行成功')
        else:
            self.text_browser.moveCursor(QTextCursor.End)
            self.text_browser.append('执行失败,影响0条记录')

8、代码输入框

  • 显示初始值
    PyQt5 快速开发 - 学生管理系统项目实战报告_第13张图片
    # 文本框
    def set_text_edit(self):
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.text_edit.setFont(font)
        self.cur.execute('show tables;')
        db_len = self.cur.fetchone()
        self.text_edit.setPlaceholderText('SELECT * FROM {};\nGO;\n\n按F5运行代码'.format(db_len[0]))

9、清空按钮与富文本浏览器

  • 这两个控件比较简单,按一下清空代码按钮就在富文本浏览器中显示信息

PyQt5 快速开发 - 学生管理系统项目实战报告_第14张图片

	# 富文本浏览器
	 def set_text_browser(self):
        self.text_browser.setPlaceholderText('操作记录:')

    # 清空按钮
    def set_clear_button(self):
        pass

    # 清空按钮左键
    def clear_all(self):
        self.text_edit.setText('')
        self.text_browser.append('清空代码区')

四、新建数据表对话框

1、添加控件

  • 界面简单,就用 Designer 添加相应控件
  • 先弄成最多只能添加三个字段
    PyQt5 快速开发 - 学生管理系统项目实战报告_第15张图片
    PyQt5 快速开发 - 学生管理系统项目实战报告_第16张图片

2、初始化对话框

class Ui_add_db_object(object):
    def __init__(self):
        super().__init__()
        self.conn = pymysql.connect(host=gl_host, port=gl_port, user=gl_user, password=gl_pwd, db=gl_db)
        self.cur = self.conn.cursor()

	# 警告信息
    @staticmethod
    def message_dialog(title, text):
        msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, title, text)
        msg_box.exec_()

3、设置控件属性

  • 设置字符长度最大值
  • 绑定确定按钮和取消按钮的信号
  • 添加下拉选项
		# 设置字符长度最大值
        if self.label_1_comboBox.currentText() == 'char' or 'text' or 'varchar':
            self.label_1_spinBox.setMaximum(255)
        else:
            self.label_1_spinBox.setMaximum(2 ** 20)
        if self.label_2_comboBox.currentText() == 'char' or 'text' or 'varchar':
            self.label_2_spinBox.setMaximum(255)
        else:
            self.label_2_spinBox.setMaximum(2 ** 20)
        if self.label_3_comboBox.currentText() == 'char' or 'text' or 'varchar':
            self.label_3_spinBox.setMaximum(255)
        else:
            self.label_3_spinBox.setMaximum(2 ** 20)
            
		# 绑定信号
        self.retranslateUi(add_db_object)
        self.add_no_pushButton_2.clicked.connect(add_db_object.close)  # type: ignore
        self.add_yes_pushButton.clicked.connect(lambda: self.add_true(add_db_object))  # type: ignore
        QtCore.QMetaObject.connectSlotsByName(add_db_object)

		# 添加数据类型下拉选项
        item_attribute = ['', 'char', 'int', 'float', 'text', 'varchar']
        self.label_1_comboBox.addItems(item_attribute)
        self.label_2_comboBox.addItems(item_attribute)
        self.label_3_comboBox.addItems(item_attribute)

4、确定按钮信号槽

  • 按下确定按钮后,检查输入的数据是否符合规范,包括:
    (1) 只有一个主键
    (2) 数据表名和字段名符合规范
    (3) 是否填入了数据
    def add_true(self, add_db_object):
        try:
        	# 每个字段的所有属性添加进一个列表
            label_1 = [self.label_1_lineEdit.text(), self.label_1_comboBox.currentText(), self.label_1_spinBox.text(),
                       self.label_1_checkBox.isChecked()]
            label_2 = [self.label_2_lineEdit.text(), self.label_2_comboBox.currentText(), self.label_2_spinBox.text(),
                       self.label_2_checkBox.isChecked()]
            label_3 = [self.label_3_lineEdit.text(), self.label_3_comboBox.currentText(), self.label_3_spinBox.text(),
                       self.label_3_checkBox.isChecked()]
            print(label_1, label_2, label_3)
            
            add_count = 0
            add_item = []
            word = r'^\w+$'
            
            # 数据表名必填
            if len(self.table_name_lineEdit.text()) == 0:
                print(self.table_name_lineEdit.text())
                match_tana = re.match(word, self.label_1_lineEdit.text())
                self.message_dialog('警告', '数据表名必填')
                return
                if match_tana is None:
                    self.message_dialog('警告', '数据表名只能是英文、数字、下划线')
                    return
                    
            # 主键只能有一个
            if self.label_1_checkBox.isChecked() and self.label_2_checkBox.isChecked() \
                    or self.label_1_checkBox.isChecked() and self.label_3_checkBox.isChecked() \
                    or self.label_2_checkBox.isChecked() and self.label_3_checkBox.isChecked():
                print('主键只能有一个')
                self.message_dialog('警告', '主键只能有一个')
                return

            else:
            	# 每个字段的字段名、字段类型、字段长度必填
                if "" not in label_1:
                    print(label_1)
                    # if len(self.label_1_lineEdit.text()) > 0:
                    match_1 = re.match(word, self.label_1_lineEdit.text())
                    if match_1 is None:
                        self.message_dialog('警告', '字段名只能是英文、数字、下划线')
                        return
                        
                    # 判断主键是否选上
                    for i in range(len(label_1) - 1):
                        add_item.append(label_1[i])
                    if self.label_1_checkBox.isChecked():
                        add_item.append('primary key')
                    else:
                        add_item.append(' ')
                    add_count += 1

                if "" not in label_2:
                    print(label_2)
                    match_2 = re.match(word, self.label_2_lineEdit.text())
                    if match_2 is None:
                        self.message_dialog('警告', '字段名只能是英文、数字、下划线')
                        return
                    for i in range(len(label_2) - 1):
                        add_item.append(label_2[i])
                    if self.label_2_checkBox.isChecked():
                        add_item.append('primary key')
                    else:
                        add_item.append(' ')
                    add_count += 1

                if "" not in label_3:
                    print(label_3)
                    match_3 = re.match(word, self.label_3_lineEdit.text())
                    if match_3 is None:
                        self.message_dialog('警告', '字段名只能是英文、数字、下划线')
                        return
                    for i in range(len(label_3) - 1):
                        add_item.append(label_3[i])
                    if self.label_3_checkBox.isChecked():
                        add_item.append('primary key')
                    else:
                        add_item.append(' ')
                    add_count += 1

            if add_count == 0:
                self.message_dialog('警告', '必填字段名、字段类型、字段长度')
                return
                
            # 执行 SQL 语句
            if len(add_item) == 4:
                self.cur.execute(
                    'create table ' + self.table_name_lineEdit.text() + '(' + add_item[0] + ' ' + add_item[1] + '(' +
                    add_item[2] + ') ' + add_item[3] + ');')
                self.conn.commit()
                self.message_dialog('提示', '添加完成,刷新数据表')
                self.cur.close()
                add_db_object.close()
            elif len(add_item) == 8:
                self.cur.execute(
                    'create table ' + self.table_name_lineEdit.text() + '(' + add_item[0] + ' ' + add_item[1] + '(' +
                    add_item[2] + ') ' + add_item[3] + ', ' + add_item[4] + ' ' + add_item[5] + '(' + add_item[
                        6] + ') ' +
                    add_item[7] + ');')
                self.conn.commit()
                self.cur.close()
                self.message_dialog('提示', '添加完成,刷新数据表')
                add_db_object.close()
            elif len(add_item) == 12:
                self.cur.execute(
                    'create table ' + self.table_name_lineEdit.text() + '(' + add_item[0] + ' ' + add_item[1] + '(' +
                    add_item[2] + ') ' + add_item[3] + ', ' + add_item[4] + ' ' + add_item[5] + '(' + add_item[
                        6] + ') ' +
                    add_item[7] + ' , ' + add_item[8] + ' ' + add_item[9] + '(' + add_item[10] + ') ' + add_item[
                        11] + ');')
                self.conn.commit()
                self.message_dialog('提示', '添加完成,刷新数据表')
                self.cur.close()
                add_db_object.close()
        except Exception as e:
            self.message_dialog('错误', e)

5、连接 UI 窗体

class AdDB(QWidget):
    def __init__(self):
        super().__init__()
        self.setFixedSize(441, 511)  # 禁止拖动
        self.setWindowIcon(QtGui.QIcon('./img/001.ico'))  # 设置窗体标题图标
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)  # 禁用最大化

五、删除记录对话框

  • 只建立了一个窗体,没有操作代码
    PyQt5 快速开发 - 学生管理系统项目实战报告_第17张图片
class Ui_delete_win(object):
    def __init__(self):
        super().__init__()
        self.conn = pymysql.connect(host=gl_host, port=gl_port, user=gl_user, password=gl_pwd, db=gl_db)
        self.cur = self.conn.cursor()

    def setupUi(self, delete_win):
        delete_win.setObjectName("delete_win")
        delete_win.resize(400, 260)
        self.delete_yes = QtWidgets.QPushButton(delete_win)
        self.delete_yes.setGeometry(QtCore.QRect(80, 200, 81, 31))
        self.delete_yes.setObjectName("delete_yes")
        self.delete_no = QtWidgets.QPushButton(delete_win)
        self.delete_no.setGeometry(QtCore.QRect(220, 200, 81, 31))
        self.delete_no.setObjectName("delete_no")
        self.delete_header = QtWidgets.QTextBrowser(delete_win)
        self.delete_header.setGeometry(QtCore.QRect(120, 20, 171, 31))
        self.delete_header.setObjectName("delete_header")
        self.widget = QtWidgets.QWidget(delete_win)
        self.widget.setGeometry(QtCore.QRect(40, 70, 331, 111))
        self.widget.setObjectName("widget")
        self.gridLayout = QtWidgets.QGridLayout(self.widget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.delete_where_vue3 = QtWidgets.QLineEdit(self.widget)
        self.delete_where_vue3.setObjectName("delete_where_vue3")
        self.gridLayout.addWidget(self.delete_where_vue3, 2, 2, 1, 1)
        self.delete_where_vue2 = QtWidgets.QLineEdit(self.widget)
        self.delete_where_vue2.setObjectName("delete_where_vue2")
        self.gridLayout.addWidget(self.delete_where_vue2, 1, 2, 1, 1)
        self.delete_where_item3 = QtWidgets.QComboBox(self.widget)
        self.delete_where_item3.setObjectName("delete_where_item3")
        self.gridLayout.addWidget(self.delete_where_item3, 2, 1, 1, 1)
        self.delete_where = QtWidgets.QLabel(self.widget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(3)
        sizePolicy.setHeightForWidth(self.delete_where.sizePolicy().hasHeightForWidth())
        self.delete_where.setSizePolicy(sizePolicy)
        self.delete_where.setObjectName("delete_where")
        self.gridLayout.addWidget(self.delete_where, 0, 0, 1, 1)
        self.delete_where_vue1 = QtWidgets.QLineEdit(self.widget)
        self.delete_where_vue1.setObjectName("delete_where_vue1")
        self.gridLayout.addWidget(self.delete_where_vue1, 0, 2, 1, 1)
        self.delete_where_item2 = QtWidgets.QComboBox(self.widget)
        self.delete_where_item2.setObjectName("delete_where_item2")
        self.gridLayout.addWidget(self.delete_where_item2, 1, 1, 1, 1)
        self.delete_where_item1 = QtWidgets.QComboBox(self.widget)
        self.delete_where_item1.setObjectName("delete_where_item1")
        self.gridLayout.addWidget(self.delete_where_item1, 0, 1, 1, 1)
        self.delete_and = QtWidgets.QLabel(self.widget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(3)
        sizePolicy.setHeightForWidth(self.delete_and.sizePolicy().hasHeightForWidth())
        self.delete_and.setSizePolicy(sizePolicy)
        self.delete_and.setObjectName("delete_and")
        self.gridLayout.addWidget(self.delete_and, 1, 0, 1, 1)
        self.delete_and_2 = QtWidgets.QLabel(self.widget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(3)
        sizePolicy.setHeightForWidth(self.delete_and_2.sizePolicy().hasHeightForWidth())
        self.delete_and_2.setSizePolicy(sizePolicy)
        self.delete_and_2.setObjectName("delete_and_2")
        self.gridLayout.addWidget(self.delete_and_2, 2, 0, 1, 1)

        self.retranslateUi(delete_win)
        self.delete_no.clicked.connect(delete_win.close)  # type: ignore
        QtCore.QMetaObject.connectSlotsByName(delete_win)

        self.delete_yes.clicked.connect(lambda: self.delete_fun())  # type: ignore

        delete_win.setTabOrder(self.delete_header, self.delete_where_item1)
        delete_win.setTabOrder(self.delete_where_item1, self.delete_where_vue1)
        delete_win.setTabOrder(self.delete_where_vue1, self.delete_where_item2)
        delete_win.setTabOrder(self.delete_where_item2, self.delete_where_vue2)
        delete_win.setTabOrder(self.delete_where_vue2, self.delete_where_item3)
        delete_win.setTabOrder(self.delete_where_item3, self.delete_where_vue3)
        delete_win.setTabOrder(self.delete_where_vue3, self.delete_yes)
        delete_win.setTabOrder(self.delete_yes, self.delete_no)

    # TODO 删除记录
    def delete_fun(self):
        print('555')

    def retranslateUi(self, delete_win):
        _translate = QtCore.QCoreApplication.translate
        delete_win.setWindowTitle(_translate("delete_win", "删除记录"))
        self.delete_yes.setText(_translate("delete_win", "确定"))
        self.delete_no.setText(_translate("delete_win", "取消"))
        self.delete_where.setText(_translate("delete_win", "where"))
        self.delete_and.setText(_translate("delete_win", "and"))
        self.delete_and_2.setText(_translate("delete_win", "and"))

class DelDB(QWidget):
    def __init__(self):
        super().__init__()
        self.setFixedSize(400, 260)  # 禁止拖动
        self.setWindowIcon(QtGui.QIcon('./img/001.ico'))  # 设置窗体标题图标
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)  # 禁用最大化

六、全部代码

#!/bin/sh
# !/usr/bin/python
# !/usr/bin/env
# -*- coding: utf-8 -*-

"""
Author: Fulling
Function: 学生管理系统
Date: 2021-12-31
"""

import sys
import pymysql
import re
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.Qt import *


class Fulling(QWidget):
    def __init__(self):
        super().__init__()
        # 窗口标题
        self.setWindowTitle('学生管理系统')
        # 窗口大小
        self.resize(720, 600)
        # 窗口居中
        self.center()
        # 图标
        self.setWindowIcon(QIcon('./img/001.ico'))
        # 连接数据库
        self.conn = pymysql.connect(host=gl_host, port=gl_port, user=gl_user, password=gl_pwd, db=gl_db)
        self.tree_view = None
        self.table_view = None
        self.queryModel = None
        self.text_edit = None
        self.run_button = None
        self.row = None
        self.vol = None
        self.text_browser = None
        self.clear_button = None
        self.add_db_view = None
        self.del_db_view = None
        self.cur = self.conn.cursor()
        self.init_ui()

    # 设置窗口主要部件和信号
    def init_ui(self):
        # 创建窗口
        self.create_window()
        # 设置树
        self.set_tree_view()
        # 设置表格
        self.set_table_view()
        # 设置文本框
        self.set_text_edit()
        # 创建运行按钮
        self.set_run_button()
        # 创建清空按钮
        self.set_clear_button()
        # 创建查看文本
        self.set_text_browser()

        # TODO 信号槽
        self.tree_view.clicked.connect(self.on_tree_clicked)
        self.run_button.clicked.connect(self.run_program)
        self.clear_button.clicked.connect(self.clear_all)

        # 右键
        self.tree_view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tree_view.customContextMenuRequested.connect(self.right_menu_show)
        # self.text_edit.setContextMenuPolicy(Qt.CustomContextMenu)
        # self.text_edit.customContextMenuRequested[QtCore.QPoint].connect(self.text_right_menu)

        # 快捷键
        self.run_button.setShortcut('F5')

    # 窗口居中
    def center(self):
        """
        窗口居中
        :return:
        """
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move(round((screen.width() - size.width()) / 2), round((screen.height() - size.height()) / 2))

    # 窗口布局
    def create_window(self):
        # 设置树属性
        self.tree_view = QTreeWidget()
        # 设置表格属性
        self.table_view = QTableWidget()
        # 设置文本框
        self.text_edit = QTextEdit()
        # 设置运行按钮
        self.run_button = QPushButton('运行所有代码')
        # 设置清空按钮
        self.clear_button = QPushButton('清空代码')
        # 设置查看文本
        self.text_browser = QTextBrowser()
        # 表格宽度自适应
        self.table_view.horizontalHeader().setStretchLastSection(True)
        self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # 左侧布局
        left_layout = QVBoxLayout()
        left_layout.addWidget(self.tree_view, 15)
        left_layout.addWidget(self.text_browser, 9)

        # 右中
        mid_layout = QHBoxLayout()
        mid_layout.addWidget(self.run_button)
        mid_layout.addWidget(self.clear_button)
        mid_layout.addWidget(QSplitter())

        # 右侧布局
        right_layout = QVBoxLayout()
        right_layout.addWidget(self.table_view, 15)
        right_layout.addLayout(mid_layout, 1)
        right_layout.addWidget(self.text_edit, 8)

        # 创建界面
        layout = QHBoxLayout(self)
        layout.addLayout(left_layout, 1)
        layout.addLayout(right_layout, 3)
        self.setLayout(layout)

    # 表格填充内容
    def table_data(self, i, j, data):
        item = QtWidgets.QTableWidgetItem()
        self.table_view.setItem(i, j, item)
        item = self.table_view.item(i, j)
        item.setText(str(data))

    # 运行查询
    def select_run(self):
        try:
            total = self.cur.fetchall()
            col_result = self.cur.description
            self.row = self.cur.rowcount  # 取得记录个数,用于设置表格的行数
            if self.row == 0:
                self.text_browser.moveCursor(QTextCursor.End)
                self.text_browser.append('数据表中没有任何记录')
            else:
                self.vol = len(total[0])  # 取得字段数,用于设置表格的列数
                col_result = list(col_result)
                a = 0
                self.table_view.setColumnCount(self.vol)
                self.table_view.setRowCount(self.row)
                for i in col_result:  # 设置表头信息,将mysql数据表中的表头信息拿出来,放进TableWidget中
                    item = QtWidgets.QTableWidgetItem()
                    self.table_view.setHorizontalHeaderItem(a, item)
                    item = self.table_view.horizontalHeaderItem(a)
                    item.setText(i[0])
                    a = a + 1

                total = list(total)  # 将数据格式改为列表形式,其是将数据库中取出的数据整体改为列表形式
                for i in range(len(total)):  # 将相关的数据
                    total[i] = list(total[i])  # 将获取的数据转为列表形式
                for i in range(self.row):
                    for j in range(self.vol):
                        self.table_data(i, j, total[i][j])
        except Exception as e:
            print(e)

    # 表格
    def set_table_view(self):
        self.cur.execute('show tables')
        db_len = self.cur.fetchone()
        self.cur.execute('select * from ' + db_len[0])  # 将数据从数据库中拿出来
        self.select_run()

    # 树
    def set_tree_view(self):
        # 树行数
        self.tree_view.setColumnCount(1)
        # 树标题
        self.tree_view.setHeaderLabel(gl_db + '.db')
        # 设置根节点
        root = QtWidgets.QTreeWidgetItem(self.tree_view)
        root.setText(0, '表')  # 只有一列
        root.setIcon(0, QIcon('img/db_logo.png'))
        # 创建游标
        cursor = self.conn.cursor()
        cursor.execute("show tables;")
        res = cursor.fetchall()
        # 遍历表
        for i in range(len(res)):
            child = QtWidgets.QTreeWidgetItem(root)  # 指定父目录
            child.setText(0, res[i][0])
            child.setText(1, '{}'.format(i + 1))
            child.setIcon(0, QIcon('img/table_logo.png'))
        # 树默认收缩
        root.setExpanded(False)
        # 树根节点
        self.tree_view.addTopLevelItem(root)

    # 文本框
    def set_text_edit(self):
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(14)
        self.text_edit.setFont(font)
        self.cur.execute('show tables;')
        db_len = self.cur.fetchone()
        self.text_edit.setPlaceholderText('SELECT * FROM {};\nGO;\n\n按F5运行代码'.format(db_len[0]))

    # 文本浏览
    def set_text_browser(self):
        self.text_browser.setPlaceholderText('操作记录:')

    # 清空按钮
    def set_clear_button(self):
        pass

    # 清空按钮左键
    def clear_all(self):
        self.text_edit.setText('')
        self.text_browser.append('清空代码区')

    # 警告信息
    @staticmethod
    def message_dialog(title, text):
        msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, title, text)
        msg_box.exec_()

    # 查询影响行
    def row_ref(self):
        cur_count = self.cur.rowcount
        if cur_count > 0:
            self.conn.commit()
            self.text_browser.moveCursor(QTextCursor.End)
            self.text_browser.append('执行成功')
        else:
            self.text_browser.moveCursor(QTextCursor.End)
            self.text_browser.append('执行失败,影响0条记录')

    # 运行按钮样式
    def set_run_button(self):
        pass

    # 运行左键
    def run_program(self):
        try:
            # 获取填写的代码
            text = self.text_edit.toPlainText()
            # 删掉所有的换行
            text = text.replace('\n', '')
            # 所有代码大写
            text = text.upper()
            # 不同代码分片
            texts = text.split(';')
            for i in range(len(texts)):
                try:
                    if texts[i][:6] == 'SELECT':
                        print('执行查询{}'.format(texts[i]))
                        self.cur.execute(texts[i])  # 将数据从数据库中拿出来
                        self.select_run()
                        self.text_browser.moveCursor(QTextCursor.End)
                        self.text_browser.append('查询{}'.format(texts[i]))
                        self.row_ref()
                    elif texts[i][:6] == 'UPDATE':
                        print('执行更新{}'.format(texts[i]))
                        self.cur.execute(texts[i])  # 将数据从数据库中拿出来
                        self.text_browser.moveCursor(QTextCursor.End)
                        self.text_browser.append('更新{}'.format(texts[i]))
                        self.row_ref()
                    elif texts[i][:6] == 'INSERT':
                        print('执行插入{}'.format(texts[i]))
                        self.cur.execute(texts[i])  # 将数据从数据库中拿出来
                        self.text_browser.moveCursor(QTextCursor.End)
                        self.text_browser.append('插入{}'.format(texts[i]))
                        self.row_ref()
                    elif texts[i][:6] == 'DELETE':
                        print('执行删除{}'.format(texts[i]))
                        self.cur.execute(texts[i])  # 将数据从数据库中拿出来
                        self.text_browser.moveCursor(QTextCursor.End)
                        self.text_browser.append('删除{}'.format(texts[i]))
                        self.row_ref()
                    elif texts[i][:6] == 'CREATE' and texts[i].find('TABLE') != -1:
                        print('创建数据表')
                        self.cur.execute(texts[i])  # 将数据从数据库中拿出来
                        self.text_browser.moveCursor(QTextCursor.End)
                        self.text_browser.append('创建数据表{}'.format(texts[i]))
                        self.flash()
                except Exception as e:
                    if '1096' in str(e):
                        print('没有使用数据库')
                        self.message_dialog('没有使用数据库', str(e))
                    elif '1054' in str(e):
                        print('没有这个数据库')
                        self.message_dialog('没有这个数据库', str(e))
                    elif '1064' in str(e):
                        print('语法错误')
                        self.message_dialog('语法错误', str(e))
                    else:
                        print('rr', e)
                        self.message_dialog('其他错误', str(e))
            print('run', text)
        except Exception as e:
            print('e:', e)

    # 树左键单击
    def on_tree_clicked(self):
        """
        树左键单击
        :return:
        """
        try:
            item = self.tree_view.currentItem()
            if item.text(0) == '表':
                print('左键单击{}'.format(item.text(0)))
                if self.tree_view.currentItem().isExpanded():
                    self.tree_view.collapseAll()
                else:
                    self.tree_view.expandAll()
            else:
                # 数据表操作
                item = self.tree_view.currentItem()
                self.cur.execute('select * from ' + item.text(0))
                self.select_run()
                print('左键单击{}'.format(item.text(0)))
        except Exception as e:
            print('树左键单击{}'.format(e))
            self.message_dialog('提示', '请先输入数据')

    # 树右键单击
    def right_menu_show(self):
        """
        树右键单击
        :return:
        """
        try:
            item = self.tree_view.currentItem()
            if item.text(0) == '表':
                print('右键单击{}'.format(item.text(0)))
                self.contextMenu = QMenu()
                self.add_db = self.contextMenu.addAction(u'新建数据表')
                self.flash_db = self.contextMenu.addAction(u'刷新')
                self.close_db = self.contextMenu.addAction(u'退出')
                self.contextMenu.popup(QCursor.pos())
                self.add_db.triggered.connect(self.add_database)  # type:ignore
                self.flash_db.triggered.connect(self.flash)  # type:ignore
                self.close_db.triggered.connect(self.close_database)  # type:ignore
                self.contextMenu.show()

            # elif id(item.parent()) == tree_root_id:
            else:
                # TODO 数据表的右键
                print('右键单击{},序号是{}'.format(item.text(0), item.text(1)))
                self.contextMenu = QMenu()
                self.open = self.contextMenu.addAction(u'打开表')
                self.drop = self.contextMenu.addAction(u'删除表')
                self.add = self.contextMenu.addAction(u'添加记录')
                self.delete = self.contextMenu.addAction(u'删除记录')
                self.update = self.contextMenu.addAction(u'更改记录')
                self.select = self.contextMenu.addAction(u'查询记录')
                self.open.triggered.connect(self.open_table)  # type:ignore
                self.drop.triggered.connect(self.drop_table)  # type:ignore
                self.add.triggered.connect(self.add_table)  # type:ignore
                self.delete.triggered.connect(self.delete_table)  # type:ignore
                self.update.triggered.connect(self.update_table)  # type:ignore
                self.select.triggered.connect(self.select_table)  # type:ignore
                self.contextMenu.popup(QCursor.pos())
                self.contextMenu.show()

        except Exception as e:
            print(e)

    # TODO 文本右键
    def text_right_menu(self):
        pass

    # 树刷新
    def flash(self):
        """
        添加数据表后的刷新操作
        :return:
        """
        print('刷新')
        item = self.tree_view.currentItem()
        root = QtWidgets.QTreeWidgetItem(self.tree_view)
        root.setText(0, '表')  # 只有一列
        root.setIcon(0, QIcon('img/db_logo.png'))
        cursor = self.conn.cursor()
        cursor.execute("show tables;")
        res = cursor.fetchall()

        # 清除树
        curr_node = self.tree_view.currentItem()
        root_index = self.tree_view.indexOfTopLevelItem(curr_node)
        self.tree_view.takeTopLevelItem(root_index)

        for i in range(len(res)):
            child = QtWidgets.QTreeWidgetItem(root)  # 指定父目录
            child.setText(0, res[i][0])
            child.setText(1, '{}'.format(i + 1))
            child.setIcon(0, QIcon('img/table_logo.png'))

    # 新建数据表
    def add_database(self):
        try:
            self.add_db_view = AdDB()
            add_ui = Ui_add_db_object()
            add_ui.setupUi(self.add_db_view)
            self.add_db_view.show()
        except Exception as e:
            print(e)

        print('新建数据表')

    # 退出数据表
    def close_database(self):
        reply = QMessageBox.question(self, '退出', '确定退出', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        if reply == QMessageBox.Yes:
            sender = self.sender()
            main_app_db = QApplication.instance()
            main_app_db.quit()
        print('退出数据表')

    # 右键打开
    def open_table(self):
        item = self.tree_view.currentItem()
        self.cur.execute('select * from ' + item.text(0))
        self.select_run()
        print('打开 {}'.format(item.text(0)))

    # 右键删除表
    def drop_table(self):
        item = self.tree_view.currentItem()
        reply = QMessageBox.question(self, '删除表', '确定要删除吗?', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        if reply == QMessageBox.Yes:
            self.cur.execute('drop table ' + item.text(0))
            self.text_browser.append('删除表 {} 成功,右击根目录刷新'.format(item.text(0)))
        print('删除 {}'.format(item.text(0)))

    # TODO 添加记录
    def add_table(self):
        self.message_dialog('提示', '功能还没开发')
        print('添加记录')

    # TODO 删除记录
    def delete_table(self):
        try:
            self.del_db_view = DelDB()
            del_ui = Ui_delete_win()
            del_ui.setupUi(self.del_db_view)
            self.del_db_view.show()
        except Exception as e:
            print(e)
        print('删除记录')

    # TODO 更改记录
    def update_table(self):
        self.message_dialog('提示', '功能还没开发')
        print('更改记录')

    # TODO 查询记录
    def select_table(self):
        self.message_dialog('提示', '功能还没开发')
        print('查询记录')


class Ui_add_db_object(object):
    def __init__(self):
        super().__init__()
        self.conn = pymysql.connect(host=gl_host, port=gl_port, user=gl_user, password=gl_pwd, db=gl_db)
        self.cur = self.conn.cursor()

    def setupUi(self, add_db_object):
        add_db_object.setObjectName("add_db_object")
        add_db_object.setEnabled(True)
        add_db_object.resize(441, 511)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(add_db_object.sizePolicy().hasHeightForWidth())
        add_db_object.setSizePolicy(sizePolicy)
        add_db_object.setMaximumSize(QtCore.QSize(500, 600))
        add_db_object.setWindowTitle("Form")
        self.gridLayoutWidget = QtWidgets.QWidget(add_db_object)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(10, 20, 421, 431))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.label_1_len = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_1_len.setObjectName("label_1_len")
        self.gridLayout.addWidget(self.label_1_len, 4, 1, 1, 1)
        self.label_2_checkBox = QtWidgets.QCheckBox(self.gridLayoutWidget)
        self.label_2_checkBox.setObjectName("label_2_checkBox")
        self.gridLayout.addWidget(self.label_2_checkBox, 10, 1, 1, 2)
        self.label_10 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_10.setObjectName("label_10")
        self.gridLayout.addWidget(self.label_10, 8, 1, 1, 1)
        self.label_1_attribute = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_1_attribute.setObjectName("label_1_attribute")
        self.gridLayout.addWidget(self.label_1_attribute, 3, 1, 1, 1)
        self.label_2 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 6, 1, 1, 2)
        self.label_3_comboBox = QtWidgets.QComboBox(self.gridLayoutWidget)
        self.label_3_comboBox.setObjectName("label_3_comboBox")
        self.gridLayout.addWidget(self.label_3_comboBox, 13, 2, 1, 1)
        self.label_2_comboBox = QtWidgets.QComboBox(self.gridLayoutWidget)
        self.label_2_comboBox.setObjectName("label_2_comboBox")
        self.gridLayout.addWidget(self.label_2_comboBox, 8, 2, 1, 1)
        self.label_2_spinBox = QtWidgets.QSpinBox(self.gridLayoutWidget)
        self.label_2_spinBox.setObjectName("label_2_spinBox")
        self.gridLayout.addWidget(self.label_2_spinBox, 9, 2, 1, 1)
        self.label_1_lineEdit = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.label_1_lineEdit.setObjectName("label_1_lineEdit")
        self.gridLayout.addWidget(self.label_1_lineEdit, 2, 2, 1, 1)
        self.label_2_len = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_2_len.setObjectName("label_2_len")
        self.gridLayout.addWidget(self.label_2_len, 9, 1, 1, 1)
        self.label_2_lineEdit = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.label_2_lineEdit.setObjectName("label_2_lineEdit")
        self.gridLayout.addWidget(self.label_2_lineEdit, 7, 2, 1, 1)
        self.label_3_spinBox = QtWidgets.QSpinBox(self.gridLayoutWidget)
        self.label_3_spinBox.setObjectName("label_3_spinBox")
        self.gridLayout.addWidget(self.label_3_spinBox, 14, 2, 1, 1)
        self.label_3_name = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_3_name.setObjectName("label_3_name")
        self.gridLayout.addWidget(self.label_3_name, 12, 1, 1, 1)
        self.label_3_checkBox = QtWidgets.QCheckBox(self.gridLayoutWidget)
        self.label_3_checkBox.setObjectName("label_3_checkBox")
        self.gridLayout.addWidget(self.label_3_checkBox, 15, 1, 1, 2)
        self.label_3_lineEdit = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.label_3_lineEdit.setObjectName("label_3_lineEdit")
        self.gridLayout.addWidget(self.label_3_lineEdit, 12, 2, 1, 1)
        self.label_6 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_6.setObjectName("label_6")
        self.gridLayout.addWidget(self.label_6, 13, 1, 1, 1)
        self.label_3_len = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_3_len.setObjectName("label_3_len")
        self.gridLayout.addWidget(self.label_3_len, 14, 1, 1, 1)
        self.label_1 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_1.setObjectName("label_1")
        self.gridLayout.addWidget(self.label_1, 1, 1, 1, 2)
        self.label_3 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_3.setObjectName("label_3")
        self.gridLayout.addWidget(self.label_3, 11, 1, 1, 2)
        self.label_1_spinBox = QtWidgets.QSpinBox(self.gridLayoutWidget)
        self.label_1_spinBox.setObjectName("label_1_spinBox")
        self.gridLayout.addWidget(self.label_1_spinBox, 4, 2, 1, 1)
        self.label_1_comboBox = QtWidgets.QComboBox(self.gridLayoutWidget)
        self.label_1_comboBox.setMaximumSize(QtCore.QSize(16777211, 16777215))
        self.label_1_comboBox.setObjectName("label_1_comboBox")
        self.gridLayout.addWidget(self.label_1_comboBox, 3, 2, 1, 1)
        self.label_1_name = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_1_name.setObjectName("label_1_name")
        self.gridLayout.addWidget(self.label_1_name, 2, 1, 1, 1)
        self.label_1_checkBox = QtWidgets.QCheckBox(self.gridLayoutWidget)
        self.label_1_checkBox.setObjectName("label_1_checkBox")
        self.gridLayout.addWidget(self.label_1_checkBox, 5, 1, 1, 2)
        self.label_2_name = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_2_name.setObjectName("label_2_name")
        self.gridLayout.addWidget(self.label_2_name, 7, 1, 1, 1)
        self.table_name_label = QtWidgets.QLabel(self.gridLayoutWidget)
        self.table_name_label.setObjectName("table_name_label")
        self.gridLayout.addWidget(self.table_name_label, 0, 1, 1, 1)
        self.table_name_lineEdit = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.table_name_lineEdit.setObjectName("table_name_lineEdit")
        self.gridLayout.addWidget(self.table_name_lineEdit, 0, 2, 1, 1)
        self.add_yes_pushButton = QtWidgets.QPushButton(add_db_object)
        self.add_yes_pushButton.setGeometry(QtCore.QRect(90, 460, 91, 31))
        self.add_yes_pushButton.setObjectName("add_yes_pushButton")
        self.add_no_pushButton_2 = QtWidgets.QPushButton(add_db_object)
        self.add_no_pushButton_2.setGeometry(QtCore.QRect(230, 460, 91, 31))
        self.add_no_pushButton_2.setObjectName("add_no_pushButton_2")

        add_db_object.setTabOrder(self.table_name_lineEdit, self.label_1_lineEdit)
        add_db_object.setTabOrder(self.label_1_lineEdit, self.label_1_comboBox)
        add_db_object.setTabOrder(self.label_1_comboBox, self.label_1_spinBox)
        add_db_object.setTabOrder(self.label_1_spinBox, self.label_1_checkBox)
        add_db_object.setTabOrder(self.label_1_checkBox, self.label_2_lineEdit)
        add_db_object.setTabOrder(self.label_2_lineEdit, self.label_2_comboBox)
        add_db_object.setTabOrder(self.label_2_comboBox, self.label_2_spinBox)
        add_db_object.setTabOrder(self.label_2_spinBox, self.label_2_checkBox)
        add_db_object.setTabOrder(self.label_2_checkBox, self.label_3_lineEdit)
        add_db_object.setTabOrder(self.label_3_lineEdit, self.label_3_comboBox)
        add_db_object.setTabOrder(self.label_3_comboBox, self.label_3_spinBox)
        add_db_object.setTabOrder(self.label_3_spinBox, self.label_3_checkBox)
        add_db_object.setTabOrder(self.label_3_checkBox, self.add_yes_pushButton)
        add_db_object.setTabOrder(self.add_yes_pushButton, self.add_no_pushButton_2)


        if self.label_1_comboBox.currentText() == 'char' or 'text' or 'varchar':
            self.label_1_spinBox.setMaximum(255)
        else:
            self.label_1_spinBox.setMaximum(2 ** 20)
        if self.label_2_comboBox.currentText() == 'char' or 'text' or 'varchar':
            self.label_2_spinBox.setMaximum(255)
        else:
            self.label_2_spinBox.setMaximum(2 ** 20)
        if self.label_3_comboBox.currentText() == 'char' or 'text' or 'varchar':
            self.label_3_spinBox.setMaximum(255)
        else:
            self.label_3_spinBox.setMaximum(2 ** 20)

        self.retranslateUi(add_db_object)
        self.add_no_pushButton_2.clicked.connect(add_db_object.close)  # type: ignore
        self.add_yes_pushButton.clicked.connect(lambda: self.add_true(add_db_object))  # type: ignore
        QtCore.QMetaObject.connectSlotsByName(add_db_object)

        item_attribute = ['', 'char', 'int', 'float', 'text', 'varchar']
        self.label_1_comboBox.addItems(item_attribute)
        self.label_2_comboBox.addItems(item_attribute)
        self.label_3_comboBox.addItems(item_attribute)

    # 警告信息
    @staticmethod
    def message_dialog(title, text):
        msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, title, text)
        msg_box.exec_()

    def add_true(self, add_db_object):
        try:
            label_1 = [self.label_1_lineEdit.text(), self.label_1_comboBox.currentText(), self.label_1_spinBox.text(),
                       self.label_1_checkBox.isChecked()]
            label_2 = [self.label_2_lineEdit.text(), self.label_2_comboBox.currentText(), self.label_2_spinBox.text(),
                       self.label_2_checkBox.isChecked()]
            label_3 = [self.label_3_lineEdit.text(), self.label_3_comboBox.currentText(), self.label_3_spinBox.text(),
                       self.label_3_checkBox.isChecked()]
            print(label_1, label_2, label_3)
            add_count = 0
            add_item = []

            word = r'^\w+$'
            if len(self.table_name_lineEdit.text()) == 0:
                print(self.table_name_lineEdit.text())
                match_tana = re.match(word, self.label_1_lineEdit.text())
                self.message_dialog('警告', '数据表名必填')
                return
                if match_tana is None:
                    self.message_dialog('警告', '数据表名只能是英文、数字、下划线')
                    return

            if self.label_1_checkBox.isChecked() and self.label_2_checkBox.isChecked() \
                    or self.label_1_checkBox.isChecked() and self.label_3_checkBox.isChecked() \
                    or self.label_2_checkBox.isChecked() and self.label_3_checkBox.isChecked():
                print('主键只能有一个')
                self.message_dialog('警告', '主键只能有一个')
                return

            else:
                if "" not in label_1:
                    print(label_1)
                    # if len(self.label_1_lineEdit.text()) > 0:
                    match_1 = re.match(word, self.label_1_lineEdit.text())
                    if match_1 is None:
                        self.message_dialog('警告', '字段名只能是英文、数字、下划线')
                        return

                    for i in range(len(label_1) - 1):
                        add_item.append(label_1[i])
                    if self.label_1_checkBox.isChecked():
                        add_item.append('primary key')
                    else:
                        add_item.append(' ')
                    add_count += 1

                if "" not in label_2:
                    print(label_2)
                    match_2 = re.match(word, self.label_2_lineEdit.text())
                    if match_2 is None:
                        self.message_dialog('警告', '字段名只能是英文、数字、下划线')
                        return
                    for i in range(len(label_2) - 1):
                        add_item.append(label_2[i])
                    if self.label_2_checkBox.isChecked():
                        add_item.append('primary key')
                    else:
                        add_item.append(' ')
                    add_count += 1

                if "" not in label_3:
                    print(label_3)
                    match_3 = re.match(word, self.label_3_lineEdit.text())
                    if match_3 is None:
                        self.message_dialog('警告', '字段名只能是英文、数字、下划线')
                        return
                    for i in range(len(label_3) - 1):
                        add_item.append(label_3[i])
                    if self.label_3_checkBox.isChecked():
                        add_item.append('primary key')
                    else:
                        add_item.append(' ')
                    add_count += 1

            if add_count == 0:
                self.message_dialog('警告', '必填字段名、字段类型、字段长度')
                return

            if len(add_item) == 4:
                self.cur.execute(
                    'create table ' + self.table_name_lineEdit.text() + '(' + add_item[0] + ' ' + add_item[1] + '(' +
                    add_item[2] + ') ' + add_item[3] + ');')
                self.conn.commit()
                self.message_dialog('提示', '添加完成,刷新数据表')
                self.cur.close()
                add_db_object.close()
            elif len(add_item) == 8:
                self.cur.execute(
                    'create table ' + self.table_name_lineEdit.text() + '(' + add_item[0] + ' ' + add_item[1] + '(' +
                    add_item[2] + ') ' + add_item[3] + ', ' + add_item[4] + ' ' + add_item[5] + '(' + add_item[
                        6] + ') ' +
                    add_item[7] + ');')
                self.conn.commit()
                self.cur.close()
                self.message_dialog('提示', '添加完成,刷新数据表')
                add_db_object.close()
            elif len(add_item) == 12:
                self.cur.execute(
                    'create table ' + self.table_name_lineEdit.text() + '(' + add_item[0] + ' ' + add_item[1] + '(' +
                    add_item[2] + ') ' + add_item[3] + ', ' + add_item[4] + ' ' + add_item[5] + '(' + add_item[
                        6] + ') ' +
                    add_item[7] + ' , ' + add_item[8] + ' ' + add_item[9] + '(' + add_item[10] + ') ' + add_item[
                        11] + ');')
                self.conn.commit()
                self.message_dialog('提示', '添加完成,刷新数据表')
                self.cur.close()
                add_db_object.close()
        except Exception as e:
            self.message_dialog('错误', e)

    def retranslateUi(self, add_db_object):
        _translate = QtCore.QCoreApplication.translate
        self.label_1_len.setText(_translate("add_db_object", "字段长度"))
        self.label_2_checkBox.setText(_translate("add_db_object", "设为主键"))
        self.label_10.setText(_translate("add_db_object", "字段属性"))
        self.label_1_attribute.setText(_translate("add_db_object", "字段属性"))
        self.label_2.setText(_translate("add_db_object", "字段2"))
        self.label_2_len.setText(_translate("add_db_object", "字段长度"))
        self.label_3_name.setText(_translate("add_db_object", "字段名"))
        self.label_3_checkBox.setText(_translate("add_db_object", "设为主键"))
        self.label_6.setText(_translate("add_db_object", "字段属性"))
        self.label_3_len.setText(_translate("add_db_object", "字段长度"))
        self.label_1.setText(_translate("add_db_object", "字段1"))
        self.label_3.setText(_translate("add_db_object", "字段3"))
        self.label_1_name.setText(_translate("add_db_object", "字段名"))
        self.label_1_checkBox.setText(_translate("add_db_object", "设为主键"))
        self.label_2_name.setText(_translate("add_db_object", "字段名"))
        self.table_name_label.setText(_translate("add_db_object", "数据表名"))
        self.add_yes_pushButton.setText(_translate("add_db_object", "确定"))
        self.add_no_pushButton_2.setText(_translate("add_db_object", "取消"))


class AdDB(QWidget):
    def __init__(self):
        super().__init__()
        self.setFixedSize(441, 511)  # 禁止拖动
        self.setWindowIcon(QtGui.QIcon('./img/001.ico'))  # 设置窗体标题图标
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)  # 禁用最大化


class Ui_delete_win(object):
    def __init__(self):
        super().__init__()
        self.conn = pymysql.connect(host=gl_host, port=gl_port, user=gl_user, password=gl_pwd, db=gl_db)
        self.cur = self.conn.cursor()

    def setupUi(self, delete_win):
        delete_win.setObjectName("delete_win")
        delete_win.resize(400, 260)
        self.delete_yes = QtWidgets.QPushButton(delete_win)
        self.delete_yes.setGeometry(QtCore.QRect(80, 200, 81, 31))
        self.delete_yes.setObjectName("delete_yes")
        self.delete_no = QtWidgets.QPushButton(delete_win)
        self.delete_no.setGeometry(QtCore.QRect(220, 200, 81, 31))
        self.delete_no.setObjectName("delete_no")
        self.delete_header = QtWidgets.QTextBrowser(delete_win)
        self.delete_header.setGeometry(QtCore.QRect(120, 20, 171, 31))
        self.delete_header.setObjectName("delete_header")
        self.widget = QtWidgets.QWidget(delete_win)
        self.widget.setGeometry(QtCore.QRect(40, 70, 331, 111))
        self.widget.setObjectName("widget")
        self.gridLayout = QtWidgets.QGridLayout(self.widget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.delete_where_vue3 = QtWidgets.QLineEdit(self.widget)
        self.delete_where_vue3.setObjectName("delete_where_vue3")
        self.gridLayout.addWidget(self.delete_where_vue3, 2, 2, 1, 1)
        self.delete_where_vue2 = QtWidgets.QLineEdit(self.widget)
        self.delete_where_vue2.setObjectName("delete_where_vue2")
        self.gridLayout.addWidget(self.delete_where_vue2, 1, 2, 1, 1)
        self.delete_where_item3 = QtWidgets.QComboBox(self.widget)
        self.delete_where_item3.setObjectName("delete_where_item3")
        self.gridLayout.addWidget(self.delete_where_item3, 2, 1, 1, 1)
        self.delete_where = QtWidgets.QLabel(self.widget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(3)
        sizePolicy.setHeightForWidth(self.delete_where.sizePolicy().hasHeightForWidth())
        self.delete_where.setSizePolicy(sizePolicy)
        self.delete_where.setObjectName("delete_where")
        self.gridLayout.addWidget(self.delete_where, 0, 0, 1, 1)
        self.delete_where_vue1 = QtWidgets.QLineEdit(self.widget)
        self.delete_where_vue1.setObjectName("delete_where_vue1")
        self.gridLayout.addWidget(self.delete_where_vue1, 0, 2, 1, 1)
        self.delete_where_item2 = QtWidgets.QComboBox(self.widget)
        self.delete_where_item2.setObjectName("delete_where_item2")
        self.gridLayout.addWidget(self.delete_where_item2, 1, 1, 1, 1)
        self.delete_where_item1 = QtWidgets.QComboBox(self.widget)
        self.delete_where_item1.setObjectName("delete_where_item1")
        self.gridLayout.addWidget(self.delete_where_item1, 0, 1, 1, 1)
        self.delete_and = QtWidgets.QLabel(self.widget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(3)
        sizePolicy.setHeightForWidth(self.delete_and.sizePolicy().hasHeightForWidth())
        self.delete_and.setSizePolicy(sizePolicy)
        self.delete_and.setObjectName("delete_and")
        self.gridLayout.addWidget(self.delete_and, 1, 0, 1, 1)
        self.delete_and_2 = QtWidgets.QLabel(self.widget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(3)
        sizePolicy.setHeightForWidth(self.delete_and_2.sizePolicy().hasHeightForWidth())
        self.delete_and_2.setSizePolicy(sizePolicy)
        self.delete_and_2.setObjectName("delete_and_2")
        self.gridLayout.addWidget(self.delete_and_2, 2, 0, 1, 1)

        self.retranslateUi(delete_win)
        self.delete_no.clicked.connect(delete_win.close)  # type: ignore
        QtCore.QMetaObject.connectSlotsByName(delete_win)

        self.delete_yes.clicked.connect(lambda: self.delete_fun())  # type: ignore

        delete_win.setTabOrder(self.delete_header, self.delete_where_item1)
        delete_win.setTabOrder(self.delete_where_item1, self.delete_where_vue1)
        delete_win.setTabOrder(self.delete_where_vue1, self.delete_where_item2)
        delete_win.setTabOrder(self.delete_where_item2, self.delete_where_vue2)
        delete_win.setTabOrder(self.delete_where_vue2, self.delete_where_item3)
        delete_win.setTabOrder(self.delete_where_item3, self.delete_where_vue3)
        delete_win.setTabOrder(self.delete_where_vue3, self.delete_yes)
        delete_win.setTabOrder(self.delete_yes, self.delete_no)

    # TODO 删除记录
    def delete_fun(self):
        print('555')

    def retranslateUi(self, delete_win):
        _translate = QtCore.QCoreApplication.translate
        delete_win.setWindowTitle(_translate("delete_win", "删除记录"))
        self.delete_yes.setText(_translate("delete_win", "确定"))
        self.delete_no.setText(_translate("delete_win", "取消"))
        self.delete_where.setText(_translate("delete_win", "where"))
        self.delete_and.setText(_translate("delete_win", "and"))
        self.delete_and_2.setText(_translate("delete_win", "and"))


class DelDB(QWidget):
    def __init__(self):
        super().__init__()
        self.setFixedSize(400, 260)  # 禁止拖动
        self.setWindowIcon(QtGui.QIcon('./img/001.ico'))  # 设置窗体标题图标
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)  # 禁用最大化


class Ui_widget(object):
    def __init__(self):
        super().__init__()
        self.main_show = None

    def setupUi(self, widget):
        widget.setObjectName("widget")
        widget.setEnabled(True)
        widget.resize(600, 400)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(widget.sizePolicy().hasHeightForWidth())
        widget.setSizePolicy(sizePolicy)
        self.formLayoutWidget_2 = QtWidgets.QWidget(widget)
        self.formLayoutWidget_2.setGeometry(QtCore.QRect(160, 100, 281, 201))
        self.formLayoutWidget_2.setObjectName("formLayoutWidget_2")
        self.formLayout_2 = QtWidgets.QFormLayout(self.formLayoutWidget_2)
        self.formLayout_2.setContentsMargins(0, 0, 0, 0)
        self.formLayout_2.setObjectName("formLayout_2")
        self.label = QtWidgets.QLabel(self.formLayoutWidget_2)
        font = QtGui.QFont()
        font.setFamily("楷体")
        font.setPointSize(18)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.label)
        self.lineEdit = QtWidgets.QLineEdit(self.formLayoutWidget_2)
        font = QtGui.QFont()
        font.setFamily("楷体")
        font.setPointSize(18)
        self.lineEdit.setFont(font)
        self.lineEdit.setObjectName("lineEdit")
        self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.lineEdit)
        self.label_2 = QtWidgets.QLabel(self.formLayoutWidget_2)
        font = QtGui.QFont()
        font.setFamily("楷体")
        font.setPointSize(18)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_2)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.formLayoutWidget_2)
        font = QtGui.QFont()
        font.setFamily("楷体")
        font.setPointSize(18)
        self.lineEdit_2.setFont(font)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.lineEdit_2)
        self.label_4 = QtWidgets.QLabel(self.formLayoutWidget_2)
        font = QtGui.QFont()
        font.setFamily("楷体")
        font.setPointSize(18)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.label_4)
        self.label_5 = QtWidgets.QLabel(self.formLayoutWidget_2)
        font = QtGui.QFont()
        font.setFamily("楷体")
        font.setPointSize(18)
        self.label_5.setFont(font)
        self.label_5.setObjectName("label_5")
        self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.label_5)
        self.label_6 = QtWidgets.QLabel(self.formLayoutWidget_2)
        font = QtGui.QFont()
        font.setFamily("楷体")
        font.setPointSize(18)
        self.label_6.setFont(font)
        self.label_6.setObjectName("label_6")
        self.formLayout_2.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.label_6)
        self.lineEdit_3 = QtWidgets.QLineEdit(self.formLayoutWidget_2)
        font = QtGui.QFont()
        font.setFamily("楷体")
        font.setPointSize(18)
        self.lineEdit_3.setFont(font)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.lineEdit_3)
        self.lineEdit_4 = QtWidgets.QLineEdit(self.formLayoutWidget_2)
        font = QtGui.QFont()
        font.setFamily("楷体")
        font.setPointSize(18)
        self.lineEdit_4.setFont(font)
        self.lineEdit_4.setObjectName("lineEdit_4")
        self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.lineEdit_4)
        self.lineEdit_5 = QtWidgets.QLineEdit(self.formLayoutWidget_2)
        font = QtGui.QFont()
        font.setFamily("楷体")
        font.setPointSize(18)
        self.lineEdit_5.setFont(font)
        self.lineEdit_5.setObjectName("lineEdit_5")
        self.formLayout_2.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.lineEdit_5)
        self.pushButton = QtWidgets.QPushButton(widget)
        self.pushButton.setGeometry(QtCore.QRect(170, 320, 120, 40))
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(12)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(widget)
        self.pushButton_2.setGeometry(QtCore.QRect(310, 320, 120, 40))
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(12)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setObjectName("pushButton_2")
        self.label_3 = QtWidgets.QLabel(widget)
        self.label_3.setGeometry(QtCore.QRect(230, 40, 151, 31))
        font = QtGui.QFont()
        font.setFamily("黑体")
        font.setPointSize(20)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")

        # 退出事件
        self.retranslateUi(widget)
        self.pushButton_2.clicked.connect(widget.close)  # type: ignore
        QtCore.QMetaObject.connectSlotsByName(widget)

        # 登录事件
        self.pushButton.clicked.connect(self.login_in)  # type: ignore
        self.pushButton.setShortcut('Return')

    # 验证登录
    def login_in(self):
        global gl_db
        global gl_host
        global gl_pwd
        global gl_user
        global gl_port

        gl_db = self.lineEdit_5.text()
        gl_host = self.lineEdit_3.text()
        gl_pwd = self.lineEdit_2.text()
        gl_user = self.lineEdit.text()
        try:
            port = int(self.lineEdit_4.text())
            try:
                conn = pymysql.connect(host=gl_host, port=gl_port, db=gl_db, user=gl_user, password=gl_pwd)
                print('登录数据库{}成功'.format(gl_db))
                self.messageDialog('提示', '登录数据库{}成功'.format(gl_db))
                conn.close()
                del conn
                self.main_show = Fulling()
                self.main_show.show()
                mainWindow.close()
            except pymysql.err.OperationalError:
                print('由于目标计算机积极拒绝,无法连接。')
                self.messageDialog('警告', '由于目标计算机积极拒绝,无法连接。')
        except ValueError:
            print('端口号错误')
            self.messageDialog('警告', '端口号错误')
        except Exception as err:
            print('错误:', err)
            self.messageDialog('警告', str(err))

        # print(db, port, host, pwd, user)
        # print(type(db), type(port), type(host), type(pwd), type(user))

    def messageDialog(self, title, text):
        # 提示信息
        msg_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, title, text)
        msg_box.exec_()

    def retranslateUi(self, widget):
        _translate = QtCore.QCoreApplication.translate
        widget.setWindowTitle(_translate("widget", "登录 MySQL"))
        self.label.setText(_translate("widget", "账  号:"))
        self.label_2.setText(_translate("widget", "密  码:"))
        self.label_4.setText(_translate("widget", "主  机:"))
        self.label_5.setText(_translate("widget", "端口号:"))
        self.label_6.setText(_translate("widget", "数据库:"))
        self.pushButton.setText(_translate("widget", "登录"))
        self.pushButton_2.setText(_translate("widget", "退出"))
        self.label_3.setText(_translate("widget", "登录 MySQL"))


class Login(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setFixedSize(600, 400)  # 禁止拖动
        self.setWindowIcon(QtGui.QIcon('./img/001.ico'))  # 设置窗体标题图标
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)  # 禁用最大化

        # 背景图片
        image = QtGui.QPixmap()
        image.load(r'./img/login_bg.jpg')
        bg = QtGui.QPalette()
        bg.setBrush(self.backgroundRole(), QtGui.QBrush(image))
        self.setPalette(bg)
        self.setAutoFillBackground(True)


if __name__ == '__main__':
    gl_db = ''
    gl_host = ''
    gl_pwd = ''
    gl_user = ''
    gl_port = 0
    # 创建 QApplication 类的实例
    logapp = QApplication(sys.argv)
    # 创建窗体
    mainWindow = Login()
    # 关联login
    ui = Ui_widget()
    ui.setupUi(mainWindow)
    # 打开窗体
    mainWindow.show()
    # 退出窗体
    sys.exit(logapp.exec_())

你可能感兴趣的:(Python,qt,pycharm,python,qt5,gui)