Kivy GUI and Pandas: How to Build a Python Login Application

Kivy is a versatile, multi-platform GUI library renowned for its responsiveness and ability to manage multiple screens within a single application.

In this project, we’ll create a multi-screen login application using Kivy. The app will allow users to log in, sign up, and receive feedback on whether their login was successful. User information will be saved in a CSV file, and we’ll use the Pandas library to validate this information by reading the CSV data into a DataFrame. The graphical interface will be built using a .kv file.

Approach:

  1. The application will consist of three screens: one for user login, another for signing up, and a third to display whether the login was successful.
  2. User information will be stored in a CSV file.
  3. We’ll utilize the Pandas library to read the CSV file into a DataFrame and verify whether the user information already exists.
  4. If the entered information is invalid, the user will be notified through pop-up messages.
  5. The final screen will confirm whether the login was successful or not.

2. Project Structure

Your project structure should look like this:

|-- main.py
|-- login.kv
|-- login.csv
  • main.py: The main Python script containing the application logic.
  • login.kv: The Kivy file for the GUI layout.
  • login.csv: The CSV file where user data will be stored (created automatically when users sign up).

Code Explanation

main.py

# Import necessary modules
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.uix.floatlayout import FloatLayout
import pandas as pd

# Class for creating a popup window
class PopupWindow(Widget):
    def btn(self):
        popFun()

# Class for the popup layout
class P(FloatLayout):
    pass

# Function to show popup
def popFun():
    show = P()
    window = Popup(title="Popup", content=show,
                   size_hint=(None, None), size=(300, 300))
    window.open()

# Class for the login window
class loginWindow(Screen):
    email = ObjectProperty(None)
    pwd = ObjectProperty(None)

    def validate(self):
        # Read the user data from CSV
        users = pd.read_csv('login.csv')

        # Validate if the email exists in the CSV
        if self.email.text not in users['Email'].unique():
            popFun()
        else:
            sm.current = 'logdata'
            self.email.text = ""
            self.pwd.text = ""

# Class for the signup window
class signupWindow(Screen):
    name2 = ObjectProperty(None)
    email = ObjectProperty(None)
    pwd = ObjectProperty(None)

    def signupbtn(self):
        # Create a DataFrame of the new user's data
        user = pd.DataFrame([[self.name2.text, self.email.text, self.pwd.text]],
                            columns=['Name', 'Email', 'Password'])

        # Read the existing user data from CSV
        users = pd.read_csv('login.csv')

        # Check if email already exists
        if self.email.text not in users['Email'].unique():
            # Append new user data to CSV
            user.to_csv('login.csv', mode='a', header=False, index=False)
            sm.current = 'login'
            self.name2.text = ""
            self.email.text = ""
            self.pwd.text = ""
        else:
            popFun()

# Class for the screen that shows login success
class logDataWindow(Screen):
    pass

# Class for managing screens
class windowManager(ScreenManager):
    pass

# Load the .kv file
kv = Builder.load_file('login.kv')
sm = windowManager()

# Add screens to the ScreenManager
sm.add_widget(loginWindow(name='login'))
sm.add_widget(signupWindow(name='signup'))
sm.add_widget(logDataWindow(name='logdata'))

# Class that builds the GUI
class loginMain(App):
    def build(self):
        return sm

# Run the app
if __name__ == "__main__":
    loginMain().run()

login.kv

This file contains the layout for the application. Create a login.kv file in the same directory as main.py and add the following content:

WindowManager:
    loginWindow:
    signupWindow:
    logDataWindow:

<LoginWindow>:
    name: 'login'
    email: email
    pwd: pwd

    GridLayout:
        cols: 1
        GridLayout:
            cols: 2

            Label:
                text: "Email:"
            TextInput:
                id: email
                multiline: False

            Label:
                text: "Password:"
            TextInput:
                id: pwd
                multiline: False
                password: True

        Button:
            text: "Login"
            on_release:
                root.validate()

        Button:
            text: "Signup"
            on_release:
                app.root.current = "signup"


<SignupWindow>:
    name: 'signup'
    name2: name2
    email: email
    pwd: pwd

    GridLayout:
        cols: 1
        GridLayout:
            cols: 2

            Label:
                text: "Name:"
            TextInput:
                id: name2
                multiline: False

            Label:
                text: "Email:"
            TextInput:
                id: email
                multiline: False

            Label:
                text: "Password:"
            TextInput:
                id: pwd
                multiline: False
                password: True

        Button:
            text: "Signup"
            on_release:
                root.signupbtn()

        Button:
            text: "Back to Login"
            on_release:
                app.root.current = "login"

<LogDataWindow>:
    name: 'logdata'

    GridLayout:
        cols: 1

        Label:
            text: "Login Successful!"

        Button:
            text: "Back to Login"
            on_release:
                app.root.current = "login"

Running the Application

  1. Prepare the CSV File:Create an empty login.csv file in the project directory. It should have the following header:
Name,Email,Password

Run the Application:

To run the application, simply open your terminal or command prompt, navigate to the project directory, and run the following command:

python main.py
  1. Interacting with the Application:
    • Signup Screen: When you start the application, you can click the “Signup” button to create a new account. Fill in your name, email, and password, and then click “Signup”.
    • Login Screen: After signing up, you’ll be redirected to the login screen. Enter your email and password to log in.
    • Validation: If your login is successful, you’ll be taken to the “Login Successful” screen. If not, a popup will appear indicating that the email does not exist.

This is a simple demonstration of how to use Kivy and Pandas to build a GUI-based login system in Python. The application can be expanded with more features, such as password encryption, improved UI/UX, and more sophisticated data handling.

Output of the Kivy Application

Here’s how the application flow would look:

  1. Initial Login Screen:
    • When you first run the application, you’ll see the login screen with fields for entering your Email and Password.There will be two buttons: Login and Signup.
    Visual Representation:
+-------------------------------+
|           Login               |
+-------------------------------+
| Email:      [                ]|
| Password:   [                ]|
|                               |
|   [Login]  [Signup]           |
+-------------------------------+

Signup Screen:

  • When you click the Signup button, you’ll be taken to a signup screen where you can enter your Name, Email, and Password.
  • After filling in the details, click the Signup button to save your information in the CSV file. If the email is already registered, you’ll get a popup indicating that the email already exists.

Visual Representation:

+-------------------------------+
|          Signup               |
+-------------------------------+
| Name:       [                ]|
| Email:      [                ]|
| Password:   [                ]|
|                               |
|  [Signup]  [Back to Login]    |
+-------------------------------+

Popup for Invalid Email or Signup Error:

  • If the email is not found during login or if you attempt to sign up with an already registered email, a popup window will appear indicating the error.

Visual Representation

+-------------------------------+
|           Popup               |
+-------------------------------+
|    Invalid Email or Error      |
|          [Close]               |
+-------------------------------+

Login Successful Screen:

  • After successfully logging in, you’ll be taken to a screen that confirms your login.
  • You can then click the Back to Login button to return to the login screen.

Visual Representation:

+-------------------------------+
|     Login Successful!         |
+-------------------------------+
|                               |
| [Back to Login]               |
+-------------------------------+

How It Works:

  1. User Signup:
    • The user’s name, email, and password are saved into a CSV file (login.csv).
  2. User Login:
    • The application reads from the login.csv file and checks if the entered email and password match any entry.
    • If the email doesn’t exist or the password is incorrect, a popup will alert the user.

Popup Messages:

  • Popups will appear if there are any issues, like an email not being found during login or attempting to sign up with an already registered email.

    This is a basic representation of how the login application with Kivy and Pandas would work. On your system, the actual GUI will have interactive elements, and you will be able to see the screens change and popups appear based on your interactions.

    Author

    Sona Avatar

    Written by

    Leave a Reply

    Trending

    CodeMagnet

    Your Magnetic Resource, For Coding Brilliance

    Programming Languages

    Web Development

    Data Science and Visualization

    Career Section

    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
         crossorigin="anonymous"></script>