python tkinter與Mysql數據庫交互實現賬號登陸

 本例已經實現的數據庫password,數據庫的表以及表結構如下:

表中已經插入的信息:

實現思路無非是用戶完成賬戶密碼輸入並點擊登錄按鈕後,程序先進行數據庫連接,然後根據用戶提供的參數,
發出相應的查詢語句,根據返回的查詢結果給出相應的響應。

代碼實現

# -*- coding: utf-8 -*-
"""
Created on Tue Nov  6 14:29:54 2018
Description:實現tkinter的密碼驗證
                1.與數據庫驗證
Version:
    
@author: HJY
"""
import tkinter as tk
from tkinter import messagebox
import sys
import pymysql
 
class loginf():
    def __init__(self,master):
        self.master = master
        self.face = tk.Frame(self.master,)
        self.face.pack()
        
        tk.Label(self.face,text='賬戶').pack()
        self.t_account = tk.Entry(self.face,)
        self.t_account.pack()
 
        tk.Label(self.face,text='密碼').pack()
        self.t_password = tk.Entry(self.face,)
        self.t_password.pack()               
        btn_login = tk.Button(self.face,text='login',command=self.login)
        btn_login.pack()
        
        
    def login(self,):
        
        account = self.t_account.get()
        password = self.t_password.get()       
        #判空操作:略
        print(account,password)
        
        #數據庫處理
        connection = pymysql.connect(host='localhost',user='root',port=3306)
        try:
            with connection.cursor() as cursor:                
                command1 = "use password;"
                command2 = "select password from passbook where account = (%s);"                              
                cursor.execute(command1)                                
                result = cursor.execute(command2,(account))
                
            connection.close()
            
        except:
            sys.exit()
        
        else:
            if result == 0:
                print('no this account!') 
                tk.messagebox.showerror('Info',"Account Not Exist!")
            else:
                print('查找結果:',result)
                if cursor.fetchone()[0] == password:
                    print('Login successfully!')
                    tk.messagebox.showinfo('Info',"Login successfully!")                    
                    #銷毀登陸界面,生成登陸後界面
                    self.face.destroy()
                    homef(self.master)
                    
                else:
                    print('password input error')
                    tk.messagebox.showerror('Info',"Password Error!")                        
                          
class homef():
    def __init__(self,master):
        self.master = master
        self.face = tk.Frame(self.master,)
        self.face.pack()     
        btn_showinfo = tk.Button(self.face,text='info',command=self.showinfo)
        btn_showinfo.pack()
    
    def showinfo(self,):
        pass
           
       
if __name__ == '__main__':
    root = tk.Tk()
    root.title('Login with password')
    root.geometry('200x200')
    
    loginf(root)
    root.mainloop()
    

效果示例:

 

推薦閱讀: