本文主要基于PyQt5用的是qt designer,连接MySQL实现登录界面,包含注册功能,记住密码功能,说明这一切都是基于在pycharm上配置好了pyuic和qt designer
1、实际效果
界面都是用designer布局的,没有用代码去写,里面用到的信号以及功能是自己写的代码实现的。账号密码保存的在MySQL数据表里,账号是主键具有唯一性。密码设置不可见,可以记住上一次登录的密码。
注册的账号是主键具有唯一性,密码必须大于6位
2、数据库说明
2.1 连接数据库
这一步请看我写的这个博客pyqt5连接mysql数据库
2.2 生成初始表
连接到数据库成功后,需要创建一个用来存储账户密码信息的表,创建用基础的SQL语句就行了
3、注册
数据库连接后,我们可以着手第一步注册一个新账号
3.1 注册按钮实现窗口切换,信号与槽
这一步的要求是,点击注册按钮跳转到注册界面,注册成功后跳转到登录界面。实现这一过程的是QT的核心机制,信号与槽。
我们用qt designer画好登录界面和注册界面,然后用pyuic或者你用终端命令将ui文件转换成py文件。注意后面的我们的实现不要在转换的这个py文件里面实现,因为如果ui有其它改动重新生成就会影响你开始写的代码,我们要重新建一个py文件 ,比如登录界面生成的文件位login.py ,我们重新建一个call_login.py 文件来对登录界面进行功能实现,注册界面也一样。
3.3.1 跳转到注册界面代码
call_login.py完整代码
from PyQt5.QtWidgets import *
from Login_module.login import Ui_LoginUi
from Login_module.Con_MySQL import *
from Login_module.call_regist import MainRegistWindow
import sys
import configparser
global UserName
UserP = {}
class MainLoginWindow(QWidget, Ui_LoginUi):
def __init__(self, parent=None):
super(MainLoginWindow, self).__init__(parent)
self.re = MainRegistWindow()
self.setupUi(self)
self.initUi()
def initUi(self):
self.IsRememberUser()
self.UserName.setFocus()
self.UserName.setPlaceholderText("请输入账号")
self.PassWord.setPlaceholderText("请输入密码")
self.PassWord.setEchoMode(QLineEdit.Password)
self.RegistButton.clicked.connect(self.regist_button)
self.re.SuccessReg.connect(self.Success_Regist)
self.LoginButton.clicked.connect(self.login_button)
self.LogoutButton.clicked.connect(self.logout_button)
"""设置记住密码"""
def IsRememberUser(self):
config = configparser.ConfigParser()
file = config.read('user.ini')
config_dict = config.defaults()
self.account = config_dict['user_name']
self.UserName.setText(self.account)
if config_dict['remember'] == 'True':
self.passwd = config_dict['password']
self.PassWord.setText(self.passwd)
self.RememberUser.setChecked(True)
else:
self.RememberUser.setChecked(False)
"""设置配置文件格式"""
def config_ini(self):
self.account = self.UserName.text()
self.passwd = self.PassWord.text()
config = configparser.ConfigParser()
if self.RememberUser.isChecked():
config["DEFAULT"] = {
"user_name":self.account,
"password":self.passwd,
"remember":self.RememberUser.isChecked()
}
else:
config["DEFAULT"] = {
"user_name": self.account,
"password": "",
"remember": self.RememberUser.isChecked()
}
with open('user.ini', 'w') as configfile:
config.write((configfile))
print(self.account, self.passwd)
def regist_button(self):
self.re.show()
w.close()
def login_button(self):
self.sql = Oper_Mysql()
if QSqlDatabase.contains("qt_sql_default_connection"):
db = QSqlDatabase.database("qt_sql_default_connection")
else:
db = QSqlDatabase.addDatabase("QMYSQL")
Login_User = self.UserName.text()
Login_Passwd = self.PassWord.text()
if Login_User == 0 or Login_Passwd.strip() == '':
QMessageBox.information(self, "error", "输入错误")
else:
self.config_ini()
query = QSqlQuery()
query.exec_("select *from Management")
while query.next():
UserID = str(query.value("M_UserID"))
UserPasswd = query.value("M_PassWord")
UserP[UserID] = UserPasswd
length = len(UserP)
for key in UserP:
length = length - 1
if key == Login_User and UserP[Login_User] == Login_Passwd:
mess = QMessageBox()
mess.setWindowTitle("Success")
mess.setText("登录成功")
mess.setStandardButtons(QMessageBox.Ok)
mess.button(QMessageBox.Ok).animateClick(1000)
mess.exec_()
print("登录成功")
"""跳转到主界面"""
self.MainWin.show()
w.close()
return True
elif key != Login_User and length == 0:
QMessageBox.information(self, "waining", "账号不存在", QMessageBox.Ok)
return False
elif key == Login_User and UserP[Login_User] != Login_Passwd:
QMessageBox.information(self, "error!", "密码输入错误", QMessageBox.Ok)
return False
def logout_button(self):
messageBox = QMessageBox(QMessageBox.Warning, "警告", "是否退出系统!")
Qyes = messageBox.addButton(self.tr("确认"), QMessageBox.YesRole)
Qno = messageBox.addButton(self.tr("取消"), QMessageBox.NoRole)
messageBox.setDefaultButton(Qno)
messageBox.exec_()
if messageBox.clickedButton() == Qyes:
w.close()
else:
return
def Success_Regist(self):
w.show()
self.re.close()
if __name__=="__main__":
app=QApplication(sys.argv)
w=MainLoginWindow()
w.show()
sys.exit(app.exec())
3.3.2 注册界面跳转回登录界面
两种情况下会跳转回登录界面,一是点击取消,二是注册成功。这时不能向上面跳转到注册界面这么简单直接跳回登录界面,那样会造成线程死亡跳转失败。我们要将登录界面当做主窗口,注册界面当做子窗口,子窗口只发信号,主窗口执行操作。
call_regist.py完整代码
from PyQt5.QtWidgets import *
from Login_module.regist import Ui_RegistUi
from PyQt5.QtCore import pyqtSignal,Qt
from Login_module.Con_MySQL import*
class MainRegistWindow(QWidget, Ui_RegistUi):
SuccessReg = pyqtSignal()
def __init__(self, parent=None):
super(MainRegistWindow, self).__init__(parent)
self.setupUi(self)
self.initUI()
def initUI(self):
self.ReginAccount.setFocus()
self.ReginAccount.setPlaceholderText("请输入注册账户")
self.UserName.setPlaceholderText("请输入姓名")
self.PassWord.setPlaceholderText("请输入密码")
self.PassWordSure.setPlaceholderText("请确认密码")
self.PassWord.setEchoMode(QLineEdit.Password)
self.PassWordSure.setEchoMode(QLineEdit.Password)
self.comboBox.setCurrentIndex(0)
self.comboBox.activated.connect(self.emit_identity)
self.ReginAccount.textChanged.connect(self.emit_Account)
self.UserName.textChanged.connect(self.emit_Username)
self.PassWord.textChanged.connect(self.emit_Password)
self.PassWordSure.textChanged.connect(self.emit_ConPassword)
self.ConfirmButton.clicked.connect(self.emit_Confir_Button)
self.CancelButton.clicked.connect(self.emit_Cancel)
def emit_Account(self):
print("Account发生改变")
def emit_Username(self):
print("UserName发生改变")
def emit_Password(self):
print("PassWord发生改变")
def emit_ConPassword(self):
print("ConPassword发生改变")
def emit_identity(self):
print(self.comboBox.currentText())
def emit_Confir_Button(self):
if self.comboBox.currentText().strip() == '' or self.ReginAccount.text().strip() == '' or self.PassWordSure.text().strip() == '' \
or self.PassWord.text().strip() == '' or self.UserName.text().strip() == '':
try:
QMessageBox.information(self, "error", "输入有误,请重新输入")
except Exception as str:
print("输入错误 %s" % (str))
elif len(self.PassWord.text()) < 6:
QMessageBox.information(self, "warning", "密码小于6位")
elif self.PassWord.text() != self.PassWordSure.text():
try:
QMessageBox.information(self, "error", "两次密码输入不一致")
except Exception as str:
print("未知错误 %s" % (str))
else:
sql = Oper_Mysql()
query = QSqlQuery()
M_UserID = self.ReginAccount.text()
M_UserName = self.UserName.text()
M_PassWord = self.PassWord.text()
M_UserRole = self.comboBox.currentText()
s = query.exec_(
"insert into management(M_UserID, M_UserName, M_PassWord, M_UserRole) values('%s', '%s', '%s', '%s')" % (
M_UserID, M_UserName, M_PassWord, M_UserRole))
if s:
QMessageBox.information(self, "QAQ", "注册成功")
else:
QMessageBox.information(self, "QAQ", "注册失败, 该账户已经存在")
self.SuccessReg.emit()
def emit_Cancel(self):
self.SuccessReg.emit()
|