1 Environmental Construction
1.1 Python installation
This paper implements part of Python environment: Python 2.7.14, 64-bit version.
The specific installation steps are as follows: Python environment building
Attachment: Configure Python IDE, recommend PyCharm (specific IDE interface is shown below), download and click to run it.
PyCharm official download address: http://www.jetbrains.com/pycharm/download/
Official download speed may be a little slow, with Baidu cloud disk download link: http://pan.baidu.com/s/1pLC5Kdd Password: u3nb
1.2 MySQL Environment Construction
This paper implements part of MySQL environment: MySQL 5.7.13, 64-bit version.
The specific installation steps are as follows: Mysql 5.7.13-Windows Installation-Free Version Configuration Brief Introduction
I recommend an IDE: Navicat that works well with MySQL. http://pan.baidu.com/s/1nvFrKCT Password: tzr3 (PS: crackable)
1.3 Install MySQLdb
MySQLdb is an interface for Python to link Mysql database. It implements the Python database API specification V2.0, which is based on MySQL C API. If you download the installed Python version with MySQLdb module, you do not need to reconfigure the installation.
Note whether the Python and MySQL versions you install are 64-bit or 32-bit, otherwise you will get an error when installing MySQLdb.
Here we share a version of MySQL-python-1.2.5.win-amd64-py2.7.exe (PS: Up to date, free of charge, the landlord himself spent four download coins on CSDN). Link: http://pan.baidu.com/s/1nuDF6lj Password: 9xyb
2. Realization
2.1 Landing Interface
PS: The interface is ugly, but mainly for familiarity with Python basic grammar and how to operate MySQL database. Interested students can query related component attributes by themselves and beautify the interface.
Use Navicat to query user table specific data information in book database:
Functions are implemented here:
(1) Click on login, if the input username and password are consistent with the query data in the background mysql database, then the prompt box will be validated successfully; otherwise, the user name or password error will be prompted, and the validation will fail.
(2) Click on registration, jump to the registration interface, hide the landing interface.
(3) The purpose of remembering user name and password selection boxes is to show the designed login interface a little better, but not to achieve specific functions.
2.2 Registration Interface
Functions are implemented here:
(1) After the user enters the registered user name and password and clicks the confirmation registration button, the successful data insertion prompt will be printed in the IDE output box, otherwise the failed data insertion prompt will be printed.
(2) When the user clicks the return button, a login interface will be restarted for the login verification of the registered account and password.
2.3 Specific implementation of part of the code
login.py
# -*- coding: UTF-8 -*- import MySQLdb from Tkinter import * from register import * from tkFont import Font from tkMessageBox import * try: from ttk import Entry, Button except ImportError: pass class Login(object): def __init__(self): self.root = Tk() self.root.title(u'Sign in') self.root.resizable(False, False) self.root.geometry('+450+250') self.sysfont = Font(self.root, size=15) self.lb_user = Label(self.root, text=u'User name:',width = 20,height = 10,font=("Blackbody", 15, "bold")) self.lb_passwd1 = Label(self.root, text=u'') self.lb_passwd = Label(self.root, text=u'Password:',width = 20,height = 5,font=("Blackbody", 15, "bold")) self.lb_user.grid(row=0, column=0, sticky=W) self.lb_passwd1.grid(row=1, column=0, sticky=W) self.lb_passwd.grid(row=2, column=0, sticky=W) self.en_user = Entry(self.root, font=self.sysfont, width=24) self.en_passwd = Entry(self.root, font=self.sysfont, width=24) self.en_user.grid(row=0, column=1, columnspan=1) self.en_passwd.grid(row=2, column=1, columnspan=1) self.en_user.insert(0, u'enter one user name') self.en_passwd.insert(0, u'Please input a password') self.en_user.config(validate='focusin', validatecommand=lambda: self.validate_func('self.en_user'), invalidcommand=lambda: self.invalid_func('self.en_user')) self.en_passwd.config(validate='focusin', validatecommand=lambda: self.validate_func('self.en_passwd'), invalidcommand=lambda: self.invalid_func('self.en_passwd')) self.var = IntVar() self.ckb = Checkbutton(self.root, text=u'Remember user name and password', underline=0, variable=self.var,font=(15)) self.ckb.grid(row=3, column=0) self.bt_print = Button(self.root, text=u'Land') self.bt_print.grid(row=3, column=1, sticky=E, pady=50,padx = 10) self.bt_print.config(command=self.print_info) self.bt_register = Button(self.root, text=u'register') self.bt_register.grid(row=3, column=2, sticky=E, pady=50, padx=50) self.bt_register.config(command=self.register_info) # self.root.bind('<Return>', self.enter_print) self.root.mainloop() def validate_func(self, en): return False if eval(en).get().strip() != '' else True def invalid_func(self, en): value = eval(en).get().strip() if value == u'enter one user name' or value == u'Input password': eval(en).delete(0, END) if en == 'self.en_passwd': eval(en).config(show='*') def print_info(self): en1_value = self.en_user.get().strip() en2_value = self.en_passwd.get().strip() txt = u'''User name: %s \n Password : %s ''' % (self.en_user.get(), self.en_passwd.get()) if en1_value == '' or en1_value == u'enter one user name': showwarning(u'Username', u'enter one user name') elif en2_value == '' or en2_value == u'Input password': showwarning(u'No password', u'Please input a password') else: a = 0 # Open database connection db = MySQLdb.connect("localhost", "root", "root", "book") # Use cursor()Method to get operation cursor cursor = db.cursor() # SQL Query statement sql = "select * from user" try: # implement SQL Sentence cursor.execute(sql) # Get a list of all records results = cursor.fetchall() for row in results: id = row[0] name = row[1] pwd = row[2] if name == en1_value and pwd == en2_value: a = 1 print "Successful database connection and validation!!!" showinfo('Landing success!!!', txt) # # Print results # print "id=%d,name=%s,pwd=%s" % \ # (id, name, pwd) except: print "Error: unable to fecth data" # Close database connection db.close() if(a == 0): showinfo('Error in username or password!!!', txt) def register_info(self): self.rootR = Tk() loginPage(self.rootR) self.root.withdraw() def enter_print(self, event): self.print_info() if __name__ == "__main__": Login()
Registration interface register.py
# coding=utf-8 import MySQLdb from login import * from Tkinter import * import string class loginPage(object): def __init__(self, master, info='Welcome to the registration page'): self.master = master self.mainlabel = Label(master, text=info, justify=CENTER) self.mainlabel.grid(row=0, columnspan=3) self.user = Label(master, text='Registered User Name:', borderwidth=3) self.user.grid(row=1, sticky=W) self.pwd = Label(master, text='Registration password:', borderwidth=3) self.pwd.grid(row=2, sticky=W) self.userEntry = Entry(master) self.userEntry.grid(row=1, column=1, columnspan=3) self.userEntry.focus_set() self.pwdEntry = Entry(master, show='*') self.pwdEntry.grid(row=2, column=1, columnspan=3) self.loginButton = Button(master, text='Confirm registration', borderwidth=2, command=self.login) self.loginButton.grid(row=3, column=1) self.clearButton = Button(master, text='Return', borderwidth=2, command=self.clear) self.clearButton.grid(row=3, column=2) def login(self): self.username = self.userEntry.get().strip() self.passwd = self.pwdEntry.get().strip() # Open database connection db = MySQLdb.connect("localhost", "root", "root", "book") # Use cursor()Method to get operation cursor cursor = db.cursor() # SQL Insert statement sql = "INSERT INTO user(name, pwd) VALUES ('%s', '%s')" % (self.username, self.passwd) try: # implement sql Sentence cursor.execute(sql) print "Data insertion success!!!" # Submit to database for execution db.commit() except: print "Data insertion failed!!!" # Rollback in case there is any error db.rollback() # Close database connection db.close() def clear(self): self.userEntry.delete(0, END) self.pwdEntry.delete(0, END) Login() if __name__ == '__main__': root = Tk() root.title('register') myLogin = loginPage(root) # root.wait_window(myLogin.mySendMail.sendPage) mainloop()
Reference material: