Python study note _ 02: Use Tkinter to connect to the MySQL database for login and registration. _ 02 tkinter

Source: Internet
Author: User

Python study note _ 02: Use Tkinter to connect to the MySQL database for login and registration. _ 02 tkinter

1. Establish an environment

1.1 install Python

1.2 create a MySQL Environment

1.3 install MySQLdb

2. Specific implementation

2.1 login interface

2.2 registration page

2.3 Specific implementation code

 1 Environment Construction1.1 Python Installation

Python environment: Python2.7.14 and 64-bit

 

For detailed installation steps, see Python environment setup.

Appendix: Configure PythonIDE. PyCharm is recommended (for details about the IDE interface). Download and click Run to use it.

 

PyCharm official: http://www.jetbrains.com/pycharm/download/

Official download speed may be a bit slow, with Baidu cloud disk download link: http://pan.baidu.com/s/1pLC5Kdd password: u3nb

1.2 create a MySQL Environment

MySQL environment: MySQL5.7.13 and 64-bit

 

For detailed installation steps, see mysql5.7.13-windows Installation-free Configuration

Recommended a very easy to use MySQL IDE: Navicat, link: http://pan.baidu.com/s/1nvFrKCT password: tzr3 (PS: crack OH)

1.3 Install MySQLdb

MySQLdb is an interface used to connect Python to the Mysql database. It implements the Python database API Specification V2.0 and is created based on MySQL c api. If you download and install the Python version that comes with the MySQLdb module, you do not need to reconfigure the installation.

Note whether the Python and MySQL versions you have installed are 64-bit or 32-bit. Otherwise, an error is returned when installing MySQLdb.

Here to share a MySQL-python-1.2.5.win-amd64-py2.7.exe version (PS: Currently the latest Oh, free to provide, the landlord himself is in the CSDN spent four download coins to get), link: http://pan.baidu.com/s/1nuDF6lj password: 9xyb

 

 

 

2 Implementation 2.1 login interface

PS: the interface is ugly, but it is mainly used to familiarize yourself with the basic Python syntax and how to operate the MySQL database. If you are interested, you can query the related component attributes and beautify the interface.

 

Use Navicat to query the specific data of the user table in the book database:

 

Functions are implemented here:

(1) click Login. If the user name and password are the same as the query data in the mysql database in the background, the prompt box is displayed for verification. Otherwise, the user name or password is incorrect and verification fails.

(2) Click "register" to go to the registration page to hide the logon page.

(3) Remember that the user name and password selection box is designed to show a better view of the login interface, without specific functions.

2.2 registration page

 

Functions are implemented here:

(1) enter the user name and password for registration, and click OK to register. The data insertion success prompt is displayed in the IDE output box. Otherwise, the data insertion failure prompt is displayed.

(2) The user clicks the return button, and a login interface is restarted for login verification by just registering the account and password.

 

2.3 Specific implementation code

Login. py

#-*-Coding: UTF-8-*-import MySQLdbfrom Tkinter import * from register import * from tkFont import Fontfrom tkMessageBox import * try: from ttk import Entry, Buttonexcept ImportError: passclass Login (object): def _ init _ (self): self. root = Tk () self. root. title (u'login') self. root. resizable (False, False) self. root. geometry ('+ 450 + 250') self. sysfont = Font (self. root, size = 15) self. lb_user = Label (self. ro Ot, text = u'user name: ', width = 20, height = 10, font = ("", 15, "bold") self. lb_passwd1 = Label (self. root, text = u'') self. lb_passwd = Label (self. root, text = u'password: ', width = 20, height = 5, font = ("", 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 the user name ') self. en_passwd.insert (0, U' enter the password ') self. en_user.config (validate = 'focusin ', validatecommand = lambda: self. validate_func ('self. en_user'), invalidcommand = lambda: self. invalid_func ('self. en_user') self. e N_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 username and password', underline = 0, variable = self. var, font = (15) self. ckb. grid (row = 3, column = 0) self. bt_print = Button (self. root, text = u'login ') 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'registry ') 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'input Username 'or value = u'enter 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_val Ue = u'enter Username ': showwarning (u'no Username', U' enter username ') elif en2_value = ''or en2_value = u'enter password ': showwarning (u'password', U' enter password') else: a = 0 # Open Database Connection db = MySQLdb. connect ("localhost", "root", "root", "book") # Use the cursor () method to obtain the operation cursor = db. cursor () # SQL query statement SQL = "select * from user" try: # Run the SQL statement cursor.exe cute (SQL) # obtain the 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 "database connection and Verification Successful !!! "Showinfo ('login successful !!! ', Txt) # print result # print "id = % d, name = % s, pwd = % s" % \ # (id, name, pwd) T: print "Error: unable to fecth data" # disable database connection to db. close () if (a = 0): showinfo ('user name or Password error !!! ', 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 page: register. py

# Coding = utf-8import MySQLdbfrom login import * from Tkinter import * import stringclass 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 = 'user name registered: ', borderwidth = 3) self. user. grid (row = 1, sticky = W) self. pwd = Label (master, text = 'registration password: ', bo Rderwidth = 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, te Xt = 'failed', 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 the database connection db = MySQLdb. connect ("localhost", "root", "root", "book") # Use the cursor () method to obtain the operation cursor = db. cursor () # SQL insert statement SQL = "INSERT INTO user (name, pwd) VALUES ('% s',' % s')" % (self. username, self. passwd) try: # Run the SQL statement cursor.exe cute (SQL) print "data is inserted successfully !!! "# Submit to the database and execute db. commit () commit T: print" data insertion failed !!! "# Rollback in case there is any error db. rollback () # disable database connection to db. close () def clear (self): self. userEntry. delete (0, END) self. pwdEntry. delete (0, END) Login () if _ name _ = '_ main _': root = Tk () root. title ('registration') myLogin = loginPage (root) # root. wait_window (myLogin. mySendMail. sendPage) mainloop ()

 

 

 

 

References:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.