Previous article: Python custom modules and packages designed English vocabulary book (file version) – CSDN Blog
Following the previous blog post, when we are proficient in custom modules and packages, mastering the reading and writing of files, mastering the regular expression built-in module “re”, and mastering the GUI (graphical interface) part After components, we then combine the above knowledge points to design a GUI (graphical interface) login interface. Let’s see how I complete the design in one step or two…
1. Work display
1. Operation results
2. Design code
""" Account password login """ # Wildcard '*' __all__ = ['main'] # get verification code def getVerifyCode(object): from small function package.verification code import verify_code object.set(verify_code.verify_code(6)) return verify_code.verify_code(6) #Read file data def readFileData(): from small function package.File operation import ReadFileData as read data = read.readlinesData(userDataPath, []) if data != 'File does not exist': global userData userData = data # Find account def findID(id): readFileData() # Read file data # Find account for i in userData: if i.strip('\\ ').split(' ')[0] == id: return i.strip('\\ ').split(' ') return None #Account login def IDenter(ID, password, inputVerify, verifyCode, label): # print(ID.get(), password.get(), inputVerify.get(), verifyCode.get(), label.get()) # Check if the account exists data = findID(ID.get()) # proofreading account if data: # proofread password if data[1] == password.get(): # Proofread verification code import re if re.findall(verifyCode.get(), inputVerify.get(), re.I): label.set('Login successful') #Initialize input box ID.set('') password.set('') inputVerify.set('') # incorrect verification code else: label.set('Verification code input error') inputVerify.set('') # Incorrect password else: label.set('Password input error') password.set('') #Account input error else: label.set('Account name input error') ID.set('') getVerifyCode(verifyCode) # Update verification code # account registration def IDregister(ID, password, inputVerify, verifyCode, label): # print(ID.get(), password.get(), inputVerify.get(), verifyCode.get(), label.get()) # Check if the account exists data = findID(ID.get()) # Prevent the account password from entering special characters and spaces ' ' import re IDdata = re.findall(r'\W', ID.get()) passwordData = re.findall(r'\W', password.get()) if ' ' in IDdata: label.set('Account names cannot use spaces') ID.set('') elif ' ' in passwordData: label.set('Password cannot use spaces') password.set('') # Prevent the input content from being empty'' elif not ID.get(): label.set('Account name cannot be empty') elif not password.get(): label.set('Password cannot be empty') # proofreading account elif not data: # Proofread verification code import re if re.findall(verifyCode.get(), inputVerify.get(), re.I): # Save to list userData.append(f'{ID.get()} {password.get()}') label.set('Account registration successful') #Initialize input box ID.set('') password.set('') inputVerify.set('') # Update file data from small function package.File operation import WriteFileData WriteFileData.writelinesData(userDataPath, userData) # incorrect verification code else: label.set('Verification code input error') inputVerify.set('') #Account input error else: label.set('This account name has been registered') ID.set('') getVerifyCode(verifyCode) # Update verification code #Global variables userDataPath = '.\..\user data\data.txt' userData = [] # Main function def main(): import tkinter as tk base = tk.Tk() # Create a new window base.title('Account and password login') # Title #Global variables labelData = tk.StringVar() # Label data ID = tk.StringVar() #Account data password = tk.StringVar() # Password data inputVerifyCode = tk.StringVar() # Enter verification code data verifyCode = tk.StringVar() # Verification code #Initialization settings verifyCode.set(getVerifyCode(verifyCode)) #Initial verification code labelData.set('Welcome to [Zhou Hua 2022 Blog] client') # tag prompt textLabel = tk.Label(base, textvariable=labelData, height=2) # Text label textLabel.pack() # account------------------------------------------------ ---------------------------- IDframe = tk.Frame(base, pady=8) # Account frame IDframe.pack() #Account tag IDlabel = tk.Label(IDframe, text='Account') IDlabel.pack(side=tk.LEFT) #Account text box IDentry = tk.Entry(IDframe, text=ID, highlightthickness=1) IDentry.pack(side=tk.RIGHT) # password------------------------------------------------ -------------------------- passwordFrame = tk.Frame(base, pady=8) # Password frame passwordFrame.pack() # password tag passwordLabel = tk.Label(passwordFrame, text='password') passwordLabel.pack(side=tk.LEFT) # Password text box passwordEntry = tk.Entry(passwordFrame, text=password, highlightthickness=1, show='*') passwordEntry.pack(side=tk.RIGHT) # Verification code------------------------------------------------- ---------------------------------- verifyFrame = tk.Frame(base, pady=6) # Verification code frame verifyFrame.pack() # Verification code label verifyLabel = tk.Label(verifyFrame, text='Verification code') verifyLabel.pack(side=tk.LEFT) # Verification code text box verifyEntry = tk.Entry(verifyFrame, text=inputVerifyCode, highlightthickness=1, width=9) verifyEntry.pack(side=tk.LEFT) # Verification code update 1 image = tk.PhotoImage(file='.\..\photo\refresh.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) # Verification code update 2 verifyUpdata = tk.Button(verifyFrame, textvariable=verifyCode, relief=tk.FLAT) verifyUpdata.config(command=lambda: getVerifyCode(verifyCode), width=7) verifyUpdata.pack() # button------------------------------------------------ ---------------------------------- buttonFrame = tk.Frame(base, padx=60, pady=10) # Button frame buttonFrame.pack() #Account login button enterButton = tk.Button(buttonFrame, text='Login') enterButton.config(command=lambda: IDenter(ID, password, inputVerifyCode, verifyCode, labelData)) enterButton.pack(side=tk.LEFT) # Blank label (separates buttons) blankLabel = tk.Label(buttonFrame, width=6) blankLabel.pack(side=tk.LEFT) #Account registration button registerButton = tk.Button(buttonFrame, text='Register') registerButton.config(command=lambda: IDregister(ID, password, inputVerifyCode, verifyCode, labelData)) registerButton.pack() base.mainloop() # Loop running window # Code testing if __name__ == '__main__': main()
3. Module design. The current mini program only uses two modules: file operation.py and verification code.py
① Module 1: File Operation.py
""" File operation module """ # Wildcard '*' variable definition __all__ = ['main'] # Get the absolute path------------------------------------------------- -------------------------- __all__.append('getAbsPath') # Wildcard character '*' to add elements def getAbsPath(path): import os, sys return os.path.abspath(sys.path[0] + path) # Create new directory file------------------------------------------------- -------------------------- __all__.append('makeDirFile') # Wildcard character '*' to add elements def makeDirFile(path): # Path splitting dirPath = '' for i in path.split('\')[:-1:]: dirPath + = i + '\' makeDir(dirPath) # Create a new directory makeFile(path) # Create a new file # Create new directory------------------------------------------------- ---------------------------------- __all__.append('makeDir') # Wildcard character '*' to add elements def makeDir(path): path = getAbsPath(path) # Get the absolute path # Determine whether the file exists, otherwise create a new directory import os if not os.path.exists(path): os.mkdir(path) # create a new file----------------------------------------------- ---------------------------------- __all__.append('makeFile') # Wildcard character '*' to add elements def makeFile(path): path = getAbsPath(path) # Get the absolute path # Determine whether the file exists, otherwise create a new file import os if not os.path.exists(path): file = open(file=path, mode='w') file.close() #Read file data============================================== ============================ __all__.append('ReadFileData') # Wildcard character '*' to add elements class ReadFileData: # Construction method def __init__(self): pass # Read the file line data and return the read data----------------------------------------- ------------------ @classmethod def readlinesData(cls, path, container): data = container if container == list(): # Variable assignment data = [] path = getAbsPath(path) # Get the absolute path # Determine whether the file exists import os if not os.path.exists(path): return 'File does not exist' #Read file data with open(path, encoding='utf-8') as file: for i in file: if container == str(): # String container data + = i elif container == list(): # List container data.append(i) else: print('The storage read data type must be string str() or list list()') return data # Read the file line data and return the read data----------------------------------------- ------------------ @classmethod def readSplitData(cls, path, split, container): if container == list(): data = [] elif container == dict(): data = dict() path = getAbsPath(path) # Get the absolute path # Determine whether the file exists import os if not os.path.exists(path): return 'File does not exist' #Read file data 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('The storage read data type must be list() or dictionary dict()') return data #Write file data================================================ ============================ __all__.append('WriteFileData') # Wildcard character '*' to add elements class WriteFileData: # Construction method def __init__(self): pass #Write file line data------------------------------------------------- -------------------------- @classmethod def writelinesData(cls, path, data): makeDirFile(path) # Create new directories and files path = getAbsPath(path) # Get the absolute path #Write file data with open(path, 'w', encoding='utf-8') as file: if type(data) == str: file.write(data) if data[-1] != '\\ ': file.write('\\ ') elif type(data) == list: for i in data: file.write(i) if i[-1] != '\\ ' and i == data[-1]: file.write('\\ ') else: print('The written data type must be string str() or list list()') #Write file line data------------------------------------------------- -------------------------- @classmethod def writeSplitData(cls, path, data, split): makeDirFile(path) # Create new directories and files path = getAbsPath(path) # Get the absolute path #Write file data 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] != '\\ ' and i[-1] == j: file.write('\\ ') 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] != '\\ ': file.write('\\ ') else: print('The writing data type must be list() or dictionary dict()') # Main function + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + def main(): print(ReadFileData.readlinesData('.\..\Hex color code.txt', '')) print(ReadFileData.readSplitData('.\..\Hex color code.txt', ', ', dict())) data = ReadFileData.readlinesData('.\..\Hex color code.txt', '') WriteFileData.writelinesData('.\..\123\456.txt', data) data2 = ReadFileData.readSplitData('.\..\hex color code.txt', ', ', dict()) WriteFileData.writeSplitData('.\..\456\789.txt', data2, '(*)') # Code testing if __name__ == '__main__': main() else: print(f'Import"{__name__}"module')
② Module 2: Verification code.py
""" Get verification code module """ # This attribute is defined to facilitate the use of the wildcard character '*' __all__ = ['main'] # Get verification code============================================== ===================== __all__.append('verify_code') # Wildcard character '*' to add elements class verify_code: __int_list = [] # used to store numbers __str_list = [] # used to store letters __all_list = [] # Used to store numbers and letters # Add elements to the list------------------------------------------------- ---------------- @classmethod def __list_append(cls): #Initialize clear cls.__int_list = [] cls.__str_list = [] cls.__all_list = [] # Get numbers 0-9 for i in range(10): cls.__int_list.append(str(i)) # Get 26 uppercase and lowercase letters for i in range(26): cls.__str_list.append(chr(ord('a') + i)) cls.__str_list.append(chr(ord('A') + i)) #Gather together lists of numbers and letters for i in range(5): cls.__all_list.extend(cls.__int_list) cls.__all_list.extend(cls.__str_list) # Get list elements------------------------------------------------- ---------------- @classmethod def get_list_element(cls, list, int): import random code = '' for i in range(int): code + = random.choice(list) return code # Purely obtain digital verification code------------------------------------------------- ------------------ @classmethod def int_sequence(cls, int=6): cls.__list_append() # Add elements to the list # Get the elements of the list return cls.get_list_element(cls.__int_list, int) # Get the pure letter verification code-------------------------------------------------- ------------------ @classmethod def str_sequence(cls, int=6): cls.__list_append() # Add elements to the list # Get the elements of the list return cls.get_list_element(cls.__str_list, int) # Get the numerical and alphabetic verification code---------------------------------------------- ------------- @classmethod def verify_code(cls, int=6): cls.__list_append() # Add elements to the list # Get the elements of the list return cls.get_list_element(cls.__all_list, int) # Main function + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + def main(): print(verify_code.int_sequence()) print(verify_code.str_sequence()) print(verify_code.verify_code()) # Code testing================================================ =========================== if __name__ == '__main__': main() else: print(f'Import"{__name__}"module')
4. Picture file: refresh.png (size: 20×20)
Author: Zhou Hua
Creation date: 2023/10/26
The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeHomepageOverview 383694 people are learning the system