上一篇:Python 自定义模块和包设计英语生词本(文件版)-CSDN博客
紧接上一篇博文,当我们熟练掌握自定义模块和包、掌握文件的的读取与写入、掌握正则表达式内置模块”re”、掌握GUI(图形界面)的部分组件后,接着我们将要以上的知识点结合起来,设计一个GUI(图形界面)登录界面。且看我如何一步两步……完成设计吧。
一、作品展示
1.运行结果
2.设计代码
"""
账户密码登录
"""
# 通配符 '*'
__all__ = ['main']
# 获取验证码
def getVerifyCode(object):
from 小功能包.验证码 import verify_code
object.set(verify_code.verify_code(6))
return verify_code.verify_code(6)
# 读取文件数据
def readFileData():
from 小功能包.文件操作 import ReadFileData as read
data = read.readlinesData(userDataPath, [])
if data != '文件不存在':
global userData
userData = data
# 查找账户
def findID(id):
readFileData() # 读取文件数据
# 查找账户
for i in userData:
if i.strip('\n').split(' ')[0] == id:
return i.strip('\n').split(' ')
return None
# 账户登录
def IDenter(ID, password, inputVerify, verifyCode, label):
# print(ID.get(), password.get(), inputVerify.get(), verifyCode.get(), label.get())
# 查找账户是否存在
data = findID(ID.get())
# 校对账户
if data:
# 校对密码
if data[1] == password.get():
# 校对验证码
import re
if re.findall(verifyCode.get(), inputVerify.get(), re.I):
label.set('登录成功')
# 初始化输入框
ID.set('')
password.set('')
inputVerify.set('')
# 验证码输入错误
else:
label.set('验证码输入错误')
inputVerify.set('')
# 密码输入错误
else:
label.set('密码输入错误')
password.set('')
# 账户输入错误
else:
label.set('账户名输入错误')
ID.set('')
getVerifyCode(verifyCode) # 更新验证码
# 账户注册
def IDregister(ID, password, inputVerify, verifyCode, label):
# print(ID.get(), password.get(), inputVerify.get(), verifyCode.get(), label.get())
# 查找账户是否存在
data = findID(ID.get())
# 防止账户密码输入特殊字符空格' '
import re
IDdata = re.findall(r'\W', ID.get())
passwordData = re.findall(r'\W', password.get())
if ' ' in IDdata:
label.set('账户名不能使用空格')
ID.set('')
elif ' ' in passwordData:
label.set('密码不能使用空格')
password.set('')
# 防止输入内容为空''
elif not ID.get():
label.set('账户名不能为空')
elif not password.get():
label.set('密码不能为空')
# 校对账户
elif not data:
# 校对验证码
import re
if re.findall(verifyCode.get(), inputVerify.get(), re.I):
# 保存到列表中
userData.append(f'{ID.get()} {password.get()}')
label.set('账户注册成功')
# 初始化输入框
ID.set('')
password.set('')
inputVerify.set('')
# 更新文件数据
from 小功能包.文件操作 import WriteFileData
WriteFileData.writelinesData(userDataPath, userData)
# 验证码输入错误
else:
label.set('验证码输入错误')
inputVerify.set('')
# 账户输入错误
else:
label.set('该账户名已注册')
ID.set('')
getVerifyCode(verifyCode) # 更新验证码
# 全局变量
userDataPath = '.\\..\\user data\\data.txt'
userData = []
# 主函数
def main():
import tkinter as tk
base = tk.Tk() # 新建窗口
base.title('账户密码登录') # 标题
# 全局变量
labelData = tk.StringVar() # 标签数据
ID = tk.StringVar() # 账号数据
password = tk.StringVar() # 密码数据
inputVerifyCode = tk.StringVar() # 输入验证码数据
verifyCode = tk.StringVar() # 验证码
# 初始化设置
verifyCode.set(getVerifyCode(verifyCode)) # 初始验证码
labelData.set('欢迎来到【周华2022博客】客户端')
# 标签提示语
textLabel = tk.Label(base, textvariable=labelData, height=2) # 文本标签
textLabel.pack()
# 账号 ----------------------------------------------------------------------------
IDframe = tk.Frame(base, pady=8) # 账号框架
IDframe.pack()
# 账号标签
IDlabel = tk.Label(IDframe, text='账户')
IDlabel.pack(side=tk.LEFT)
# 账号文本框
IDentry = tk.Entry(IDframe, text=ID, highlightthickness=1)
IDentry.pack(side=tk.RIGHT)
# 密码 -----------------------------------------------------------------------------
passwordFrame = tk.Frame(base, pady=8) # 密码框架
passwordFrame.pack()
# 密码标签
passwordLabel = tk.Label(passwordFrame, text='密码')
passwordLabel.pack(side=tk.LEFT)
# 密码文本框
passwordEntry = tk.Entry(passwordFrame, text=password, highlightthickness=1, show='*')
passwordEntry.pack(side=tk.RIGHT)
# 验证码 -----------------------------------------------------------------------------
verifyFrame = tk.Frame(base, pady=6) # 验证码框架
verifyFrame.pack()
# 验证码标签
verifyLabel = tk.Label(verifyFrame, text='验证码')
verifyLabel.pack(side=tk.LEFT)
# 验证码文本框
verifyEntry = tk.Entry(verifyFrame, text=inputVerifyCode, highlightthickness=1, width=9)
verifyEntry.pack(side=tk.LEFT)
# 验证码更新1
image = tk.PhotoImage(file='.\\..\\photo\\刷新.png')
updataButton = tk.Button(verifyFrame, textvariable=verifyCode, relief=tk.FLAT)
updataButton.config(image=image, width=20, height=20)
updataButton.config(command=lambda: getVerifyCode(verifyCode))
updataButton.pack(side=tk.LEFT)
# 验证码更新2
verifyUpdata = tk.Button(verifyFrame, textvariable=verifyCode, relief=tk.FLAT)
verifyUpdata.config(command=lambda: getVerifyCode(verifyCode), width=7)
verifyUpdata.pack()
# 按钮 ------------------------------------------------------------------------------
buttonFrame = tk.Frame(base, padx=60, pady=10) # 按钮框架
buttonFrame.pack()
# 账号登录按钮
enterButton = tk.Button(buttonFrame, text='登录')
enterButton.config(command=lambda: IDenter(ID, password, inputVerifyCode, verifyCode, labelData))
enterButton.pack(side=tk.LEFT)
# 空白标签(隔开按钮)
blankLabel = tk.Label(buttonFrame, width=6)
blankLabel.pack(side=tk.LEFT)
# 账号注册按钮
registerButton = tk.Button(buttonFrame, text='注册')
registerButton.config(command=lambda: IDregister(ID, password, inputVerifyCode, verifyCode, labelData))
registerButton.pack()
base.mainloop() # 循环运行窗口
# 代码测试
if __name__ == '__main__':
main()
3.模块设计,当前小程序只用了两个模块:文件操作.py、验证码.py
① 模块一:文件操作.py
"""
文件操作模块
"""
# 通配符'*'变量定义
__all__ = ['main']
# 获取绝对路径 ------------------------------------------------------------------------
__all__.append('getAbsPath') # 通配符'*'添加元素
def getAbsPath(path):
import os, sys
return os.path.abspath(sys.path[0]+path)
# 新建目录文件 ------------------------------------------------------------------------
__all__.append('makeDirFile') # 通配符'*'添加元素
def makeDirFile(path):
# 路径分割
dirPath = ''
for i in path.split('\\')[:-1:]:
dirPath += i + '\\'
makeDir(dirPath) # 新建目录
makeFile(path) # 新建文件
# 新建目录 -----------------------------------------------------------------------------
__all__.append('makeDir') # 通配符'*'添加元素
def makeDir(path):
path = getAbsPath(path) # 获取绝对路径
# 判断文件是否存在,否则新建目录
import os
if not os.path.exists(path):
os.mkdir(path)
# 新建文件 -----------------------------------------------------------------------------
__all__.append('makeFile') # 通配符'*'添加元素
def makeFile(path):
path = getAbsPath(path) # 获取绝对路径
# 判断文件是否存在,否则新建文件
import os
if not os.path.exists(path):
file = open(file=path, mode='w')
file.close()
# 读取文件数据 =========================================================================
__all__.append('ReadFileData') # 通配符'*'添加元素
class ReadFileData:
# 构造方法
def __init__(self):
pass
# 读取文件行数据,返回读取的数据 --------------------------------------------------------
@classmethod
def readlinesData(cls, path, container):
data = container
if container == list(): # 变量赋值
data = []
path = getAbsPath(path) # 获取绝对路径
# 判断文件是否存在
import os
if not os.path.exists(path):
return '文件不存在'
# 读取文件数据
with open(path, encoding='utf-8') as file:
for i in file:
if container == str(): # 字符串容器
data += i
elif container == list(): # 列表容器
data.append(i)
else:
print('存储读取数据类型必须为字符串str()或者列表list()')
return data
# 读取文件行数据,返回读取的数据 --------------------------------------------------------
@classmethod
def readSplitData(cls, path, split, container):
if container == list():
data = []
elif container == dict():
data = dict()
path = getAbsPath(path) # 获取绝对路径
# 判断文件是否存在
import os
if not os.path.exists(path):
return '文件不存在'
# 读取文件数据
with open(path, encoding='utf-8') as file:
for i in file:
if container == list():
data.append(i.split(split))
elif container == dict():
data[i.split(split)[0]] = i.split(split)[1::]
else:
print('存储读取数据类型必须列表list()或者字典dict()')
return data
# 写入文件数据 =========================================================================
__all__.append('WriteFileData') # 通配符'*'添加元素
class WriteFileData:
# 构造方法
def __init__(self):
pass
# 写入文件行数据 --------------------------------------------------------------------
@classmethod
def writelinesData(cls, path, data):
makeDirFile(path) # 新建目录和文件
path = getAbsPath(path) # 获取绝对路径
# 写入文件数据
with open(path, 'w', encoding='utf-8') as file:
if type(data) == str:
file.write(data)
if data[-1] != '\n':
file.write('\n')
elif type(data) == list:
for i in data:
file.write(i)
if i[-1] != '\n' and i == data[-1]:
file.write('\n')
else:
print('写入数据类型必须为字符串str()或者列表list()')
# 写入文件行数据 --------------------------------------------------------------------
@classmethod
def writeSplitData(cls, path, data, split):
makeDirFile(path) # 新建目录和文件
path = getAbsPath(path) # 获取绝对路径
# 写入文件数据
with open(path, 'w', encoding='utf-8') as file:
if type(data) == list:
for i in data:
for j in i:
file.write(j)
if i[-1] != j:
file.write(split)
if j[-1] != '\n' and i[-1] == j:
file.write('\n')
elif type(data) == dict:
for i, j in data.items():
file.write(i)
for k in j:
file.write(split + k)
if k == j[-1] and k[-1] != '\n':
file.write('\n')
else:
print('写入数据类型必须为列表list()或者字典dict()')
# 主函数 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def main():
print(ReadFileData.readlinesData('.\\..\\十六进制颜色码.txt', ''))
print(ReadFileData.readSplitData('.\\..\\十六进制颜色码.txt', '、', dict()))
data = ReadFileData.readlinesData('.\\..\\十六进制颜色码.txt', '')
WriteFileData.writelinesData('.\\..\\123\\456.txt', data)
data2 = ReadFileData.readSplitData('.\\..\\十六进制颜色码.txt', '、', dict())
WriteFileData.writeSplitData('.\\..\\456\\789.txt', data2, '(*)')
# 代码测试
if __name__ == '__main__':
main()
else:
print(f'导入"{__name__}"模块')
② 模块二:验证码.py
"""
获取验证码模块
"""
# 定义此属性是为了方便使用通配符‘*’
__all__ = ['main']
# 获取验证码 ===================================================================
__all__.append('verify_code') # 通配符'*'添加元素
class verify_code:
__int_list = [] # 用于存储数字
__str_list = [] # 用于存储字母
__all_list = [] # 用于存储数字和字母
# 列表添加元素 --------------------------------------------------------------
@classmethod
def __list_append(cls):
# 初始化清空
cls.__int_list = []
cls.__str_list = []
cls.__all_list = []
# 获取0-9数字
for i in range(10):
cls.__int_list.append(str(i))
# 获取26个大小写字母
for i in range(26):
cls.__str_list.append(chr(ord('a')+i))
cls.__str_list.append(chr(ord('A')+i))
# 把数字和字母列表集合到一起
for i in range(5):
cls.__all_list.extend(cls.__int_list)
cls.__all_list.extend(cls.__str_list)
# 获取列表元素 --------------------------------------------------------------
@classmethod
def get_list_element(cls, list, int):
import random
code = ''
for i in range(int):
code += random.choice(list)
return code
# 纯获取数字验证码 -------------------------------------------------------------
@classmethod
def int_sequence(cls, int=6):
cls.__list_append() # 列表添加元素
# 获取列表的元素
return cls.get_list_element(cls.__int_list, int)
# 获取纯字母验证码 -------------------------------------------------------------
@classmethod
def str_sequence(cls, int=6):
cls.__list_append() # 列表添加元素
# 获取列表的元素
return cls.get_list_element(cls.__str_list, int)
# 获取数字和字母验证码 --------------------------------------------------------
@classmethod
def verify_code(cls, int=6):
cls.__list_append() # 列表添加元素
# 获取列表的元素
return cls.get_list_element(cls.__all_list, int)
# 主函数 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def main():
print(verify_code.int_sequence())
print(verify_code.str_sequence())
print(verify_code.verify_code())
# 代码测试 ==========================================================================
if __name__ == '__main__':
main()
else:
print(f'导入"{__name__}"模块')
4.图片文件:刷新.png(大小:20×20)
作者:周华
创作日期:2023/10/26
版权声明:本文为博主作者:周华2022原创文章,版权归属原作者,如果侵权,请联系我们删除!
原文链接:https://blog.csdn.net/zhouhua2022/article/details/134066734