1. 程式人生 > >python tkinter與Mysql資料庫互動實現賬號登陸_code

python tkinter與Mysql資料庫互動實現賬號登陸_code

 本例已經實現的資料庫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()
    

效果示例: