Thursday, June 19, 2025

CHATBOT USING TKINTER

 

CODE :

from tkinter import *


# Create main window

window = Tk()

window.title("Healthcare Chatbot")

window.geometry('600x600')

window.configure(bg='#0084ff')


# Chat log area

chat_log = Text(window, height=23, width=65, bg='#f5f5f5', font=('Helvetica', 12))

chat_log.place(x=10, y=10)


# Scrollbar

scrollbar = Scrollbar(window)

scrollbar.place(x=590, y=10, height=420)

chat_log.config(yscrollcommand=scrollbar.set)

scrollbar.config(command=chat_log.yview)


# Entry field with reduced width (shorter)

input_field = Entry(window, width=42, font=('Helvetica', 14))

input_field.place(x=10, y=510, height=35)


# Send button placed next to the input field, fixed position (not docked)

send_button = Button(window, text="Send", font=('Helvetica', 14), command=lambda: send_message())

send_button.place(x=500, y=507)


# Function to get chatbot response

def get_chatbot_response(user_input):

    user_input = user_input.lower()

    if "hello" in user_input:

        return "Hello! How can I assist you?"

    elif "how are you" in user_input:

        return "I'm just a bot, but I'm doing great! How about you?"

    elif "symptoms" in user_input:

        return "Please describe your symptoms in more detail."

    elif "headache" in user_input:

        return "It could be a migraine or tension headache. Consider taking a pain reliever and resting."

    elif "fever" in user_input:

        return "A fever could indicate an infection. Monitor your temperature and consult a doctor if it persists."

    elif "cold" in user_input:

        return "Rest, stay warm, and drink plenty of fluids. Over-the-counter cold remedies may help relieve symptoms."

    elif "cough" in user_input:

        return "A cough can be caused by many things. Try warm fluids and cough syrup. If it persists, see a doctor."

    elif "stomach pain" in user_input or "abdominal pain" in user_input:

        return "Stomach pain can have many causes like indigestion or infection. If it's severe or ongoing, seek medical advice."

    elif "diabetes" in user_input:

        return "Diabetes requires careful management of blood sugar levels through diet, medication, and exercise."

    elif "blood pressure" in user_input or "hypertension" in user_input:

        return "High blood pressure should be monitored regularly. A healthy lifestyle and medication can help control it."

    elif "covid" in user_input or "coronavirus" in user_input:

        return "COVID-19 symptoms include fever, cough, and loss of taste/smell. Isolate and get tested if you suspect infection."

    elif "allergy" in user_input:

        return "Allergies can cause sneezing, rashes, or itching. Avoid triggers and consider antihistamines."

    elif "sore throat" in user_input:

        return "Try warm saltwater gargles and stay hydrated. If the sore throat persists, consult a healthcare provider."

    elif "chest pain" in user_input:

        return "Chest pain could be serious. If it's severe, radiates, or comes with shortness of breath, seek emergency help."

    elif "vomiting" in user_input:

        return "Stay hydrated and rest. If vomiting persists or is severe, consult a doctor."

    elif "diarrhea" in user_input:

        return "Drink plenty of fluids to stay hydrated. Avoid spicy food. If it continues, seek medical advice."

    elif "back pain" in user_input:

        return "Try rest, gentle stretches, and applying heat. If pain is chronic or severe, consult a doctor."

    elif "rash" in user_input or "skin" in user_input:

        return "Skin rashes can be due to allergies or infections. Keep the area clean and avoid irritants."

    elif "asthma" in user_input:

        return "Use your inhaler as prescribed and avoid triggers like smoke and dust. Seek help if breathing worsens."

    elif "depression" in user_input:

        return "I'm sorry you're feeling this way. Consider talking to a mental health professional for support."

    elif "anxiety" in user_input:

        return "Try to relax and breathe deeply. If anxiety is affecting daily life, speak to a mental health professional."

    elif "urination" in user_input or "pee" in user_input or "urinary" in user_input:

        return "Painful or frequent urination can indicate a UTI. Drink water and consult a doctor if it persists."

    elif "eye pain" in user_input or "eyes" in user_input:

        return "Eye pain can be caused by strain, infection, or injury. Avoid screens and see a specialist if needed."

    else:

        return "I'm sorry, I don't have information on that. Can you be more specific?"


# Function to send message

def send_message():

    user_input = input_field.get()

    if user_input.strip() == "":

        return

    chat_log.insert(END, "You: " + user_input + "\n")

    input_field.delete(0, END)


    response = get_chatbot_response(user_input)

    chat_log.insert(END, "Chatbot: " + response + "\n\n")

    chat_log.see(END)


# Bind Enter key to send message

window.bind('<Return>', lambda event: send_message())


# Run the main loop

window.mainloop()


OUTPUT :




BUS TICKET BOOKING USING TKINTER

 

CODE :

from tkinter import *

from tkinter import messagebox

from tkcalendar import DateEntry  # You need to install tkcalendar using: pip install tkcalendar

from datetime import date

import sqlite3

import random

import string


# Initialize main window

top = Tk()

top.geometry('550x300')

top.title('Ticket Booking System')


# Connect to the database

conn = sqlite3.connect('ticket_booking_database.db')

cursor = conn.cursor()


# Create table if it doesn't exist

cursor.execute("""

    CREATE TABLE IF NOT EXISTS ticket (

        name TEXT,

        ticket_id TEXT PRIMARY KEY,

        ticket_date TEXT,

        ticket_validity TEXT

    )

""")


# Fetch existing ticket IDs

cursor.execute('SELECT * FROM ticket')

tickets = cursor.fetchall()

tickets_id = [i[1] for i in tickets]

conn.commit()


# UI Header

Label(top, text='Ticket Management System', font=('Arial', 18)).grid(

    row=0, column=0, columnspan=2, padx=80, pady=20

)


# Helper functions

def show_message(title, message):

    messagebox.showinfo(title, message)



def get_random_string():

    letters = string.ascii_lowercase

    return ''.join(random.choice(letters) for _ in range(8))



def Book():

    top1 = Toplevel()

    top1.geometry('350x300')

    top1.title('Book')


    name = StringVar(top1)

    ticket_id = StringVar(top1)

    ticket_date = StringVar(top1)

    ticket_date.set(date.today())

    ticket_validity = StringVar(top1)


    # Generate unique ticket ID

    while True:

        t_id = get_random_string()

        if t_id not in tickets_id:

            ticket_id.set(t_id)

            break


    def BookNow():

        if len(name.get()) < 3 or len(ticket_date.get()) < 7 or len(ticket_validity.get()) < 7:

            show_message('Error', 'Enter valid details')

            return

        try:

            conn = sqlite3.connect("ticket_booking_database.db")

            cursor = conn.cursor()

            cursor.execute(

                "INSERT INTO ticket (name, ticket_id, ticket_date, ticket_validity) VALUES (?, ?, ?, ?)",

                (name.get(), ticket_id.get(), ticket_date.get(), ticket_validity.get())

            )

            conn.commit()

            show_message('Successful', f'Booking successful!\nYour Ticket ID: {ticket_id.get()}')

            top1.destroy()

        except sqlite3.Error as e:

            show_message('Error', str(e))

        finally:

            conn.close()


    # Booking form layout

    Label(top1, text='Enter details', font=('Arial', 14)).grid(row=0, column=0, padx=10, pady=10, columnspan=2)

    Label(top1, text='Name', font=('Arial', 12)).grid(row=1, column=0, padx=10, pady=10, sticky='w')

    Entry(top1, textvariable=name).grid(row=1, column=1)


    Label(top1, text='Ticket ID', font=('Arial', 12)).grid(row=2, column=0, padx=10, pady=10, sticky='w')

    Entry(top1, textvariable=ticket_id, state='disabled').grid(row=2, column=1)


    Label(top1, text='Booking Date', font=('Arial', 12)).grid(row=3, column=0, padx=10, pady=10, sticky='w')

    DateEntry(top1, selectmode='day', textvariable=ticket_date).grid(row=3, column=1)


    Label(top1, text='Validity', font=('Arial', 12)).grid(row=4, column=0, padx=10, pady=10, sticky='w')

    DateEntry(top1, selectmode='day', textvariable=ticket_validity).grid(row=4, column=1)


    Button(top1, text='Confirm', bg='green', fg='white', font=('Arial', 14), width=10, command=BookNow).grid(row=5, column=1, pady=10)



def ViewHistory():

    top2 = Toplevel()

    top2.geometry('750x300')

    top2.title('View Ticket Booking History')


    headers = ['Customer Name', 'Ticket ID', 'Date of Booking', 'Ticket Validity(Date)']

    for i, text in enumerate(headers):

        Label(top2, text=text, font=('Arial', 12), borderwidth=1, relief="solid", width=20).grid(row=0, column=i, pady=10)


    conn = sqlite3.connect('ticket_booking_database.db')

    cursor = conn.cursor()

    cursor.execute('SELECT * FROM ticket')

    tickets = cursor.fetchall()

    conn.close()


    for i, ticket in enumerate(tickets):

        for j, item in enumerate(ticket):

            Label(top2, text=item, borderwidth=1, relief="solid", width=20).grid(row=i + 1, column=j)



def DeleteBooking():

    top3 = Toplevel()

    top3.geometry('800x300')

    top3.title('Delete Ticket Booking')


    headers = ['Customer Name', 'Ticket ID', 'Date of Booking', 'Ticket Validity(Date)', 'Action']

    for i, text in enumerate(headers):

        Label(top3, text=text, font=('Arial', 12), borderwidth=1, relief="solid", width=20).grid(row=0, column=i, pady=10)


    def delete_rows(ticket_id):

        try:

            conn = sqlite3.connect("ticket_booking_database.db")

            cursor = conn.cursor()

            cursor.execute("DELETE FROM ticket WHERE ticket_id = ?", (ticket_id,))

            conn.commit()

            show_message('Success', 'Ticket deleted successfully!')

            top3.destroy()

            DeleteBooking()  # Refresh the window

        except sqlite3.Error as e:

            show_message('Error', str(e))

        finally:

            conn.close()


    conn = sqlite3.connect('ticket_booking_database.db')

    cursor = conn.cursor()

    cursor.execute('SELECT * FROM ticket')

    tickets = cursor.fetchall()

    conn.close()


    for i, ticket in enumerate(tickets):

        for j, item in enumerate(ticket):

            Label(top3, text=item, borderwidth=1, relief="solid", width=20).grid(row=i + 1, column=j)

        Button(top3, text='Delete', command=lambda t_id=ticket[1]: delete_rows(t_id)).grid(row=i + 1, column=4)



# Main buttons

Button(top, text='Book Ticket', font=('Arial', 14), fg='white', width=12, height=2, bg='Green', command=Book).grid(row=1, column=0, padx=80, pady=20)

Button(top, text='View History', font=('Arial', 14), fg='white', width=12, height=2, bg='Green', command=ViewHistory).grid(row=1, column=1, pady=20)

Button(top, text='Delete Booking', font=('Arial', 14), fg='white', width=12, height=2, bg='Green', command=DeleteBooking).grid(row=2, column=0, pady=30)

Button(top, text='Quit', font=('Arial', 14), fg='white', width=12, height=2, bg='Green', command=top.destroy).grid(row=2, column=1, pady=30)


# Start the app

top.mainloop()


OUTPUT :

HOME PAGE :



BOOK TICKET :




BOOKING SUCCESSFUL MESSAGE :




VIEW HISTORY :





DELETE BOOKING :



AFTER DELETION :




ATM PROJECT USING TKINTER



CODE :

import tkinter as tk

from tkinter import messagebox


# Dummy data for ATM user

USER_PIN = "1234"

balance = 1000.0


# Functions

def verify_pin():

    entered_pin = pin_entry.get()

    if entered_pin == USER_PIN:

        login_window.destroy()

        open_main_menu()

    else:

        messagebox.showerror("Error", "Incorrect PIN")



def open_main_menu():

    global menu_window

    menu_window = tk.Toplevel()

    menu_window.title("ATM Main Menu")

    menu_window.geometry("300x300")


    tk.Label(menu_window, text="Welcome to R2C ATM", font=('Arial', 14)).pack(pady=10)


    tk.Button(menu_window, text="Check Balance", width=20, command=check_balance).pack(pady=5)

    tk.Button(menu_window, text="Deposit", width=20, command=deposit_money).pack(pady=5)

    tk.Button(menu_window, text="Withdraw", width=20, command=withdraw_money).pack(pady=5)

    tk.Button(menu_window, text="Exit", width=20, command=menu_window.destroy).pack(pady=5)



def check_balance():

    messagebox.showinfo("Balance", f"Your current balance is ₹{balance:.2f}")



def deposit_money():

    def perform_deposit():

        global balance

        try:

            amount = float(deposit_entry.get())

            if amount <= 0:

                raise ValueError

            balance += amount

            messagebox.showinfo("Success", f"Deposited ₹{amount:.2f} successfully!")

            deposit_win.destroy()

        except:

            messagebox.showerror("Error", "Enter a valid amount")


    deposit_win = tk.Toplevel(menu_window)

    deposit_win.title("Deposit")

    tk.Label(deposit_win, text="Enter amount to deposit:").pack(pady=5)

    deposit_entry = tk.Entry(deposit_win)

    deposit_entry.pack(pady=5)

    tk.Button(deposit_win, text="Deposit", command=perform_deposit).pack(pady=5)



def withdraw_money():

    def perform_withdraw():

        global balance

        try:

            amount = float(withdraw_entry.get())

            if amount <= 0 or amount > balance:

                raise ValueError

            balance -= amount

            messagebox.showinfo("Success", f"Withdrew ₹{amount:.2f} successfully!")

            withdraw_win.destroy()

        except:

            messagebox.showerror("Error", "Enter a valid amount within balance")


    withdraw_win = tk.Toplevel(menu_window)

    withdraw_win.title("Withdraw")

    tk.Label(withdraw_win, text="Enter amount to withdraw:").pack(pady=5)

    withdraw_entry = tk.Entry(withdraw_win)

    withdraw_entry.pack(pady=5)

    tk.Button(withdraw_win, text="Withdraw", command=perform_withdraw).pack(pady=5)



# Login Window

login_window = tk.Tk()

login_window.title("ATM Login")

login_window.geometry("300x150")


tk.Label(login_window, text="Enter PIN:", font=('Arial', 12)).pack(pady=10)

pin_entry = tk.Entry(login_window, show="*", font=('Arial', 12))

pin_entry.pack()

tk.Button(login_window, text="Login", command=verify_pin).pack(pady=10)


login_window.mainloop()


OUTPUT :


LOGIN PAGE : 




MAIN MENU :




CHECK BALANCE :



AMOUNT DEPOSIT : 



AFTER DEPOSITION :




AMOUNT WITHDRAW :







AFTER WITHDRAWAL :





Monday, January 20, 2025

PETROL BUNK BILLING SYSTEM USING PYTHON

 CODE:

from datetime import datetime

print("***Petrol Bunk Billing System***")

petrol_price = 100

diesel_price = 95

print("""

----- Menu-----

1. Petrol

2. Diesel

""")

fuel_choice = int(input("Enter your choice (1 for Petrol, 2 for Diesel): "))


if fuel_choice == 1:

    fuel_type = "Petrol"

    fuel_price = petrol_price

elif fuel_choice == 2:

    fuel_type = "Diesel"

    fuel_price = diesel_price

else:

    print("Invalid choice.")

    exit()

vehicle_number = input("Enter your vehicle number: ")

liters = int(input("Enter the liters of fuel you want: "))

total_cost = liters * fuel_price

current_datetime = datetime.now()

formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")

print(f"""

***Bharath Petroleum***

Date & Time: {formatted_datetime}

Vehicle Number: {vehicle_number}

Fuel: {fuel_type}

Quantity: {liters} liters

Rate: Rs. {fuel_price}/liter

Total Amount: Rs. {total_cost}

***Thank You . Visit Again***

""")

OUTPUT:



BUS TICKET BOOKING SYSTEM

 CODE:

class Bus:

    def __init__(self, bus_route, sp, ep, seats, cost_per_seat):

        self.bus_route = bus_route

        self.sp = sp

        self.ep = ep

        self.seats = seats

        self.available_seats = seats

        self.cost_per_seat = cost_per_seat

        self.booked_seats = [] 

    def book_seat(self, seat_number):

        if 1 <= seat_number <= self.seats:

            if seat_number not in self.booked_seats:

                self.available_seats -= 1

                self.booked_seats.append(seat_number)

                return True

            else:

                print(f"Seat {seat_number} is already booked. Please choose another seat.")

                return False

        else:

            print("Invalid seat number.")

            return False

    def __str__(self):

        return f"{self.bus_route} ({self.sp} to {self.ep}) - {self.available_seats} seats available"

def get_customer_details():

    name = input("Enter your Name: ")

    gender = input("Enter your Gender (M/F): ")

    age = int(input("Enter your Age: "))

    return name, gender, age

def generate_receipt(bus, seat_numbers, customer_name, customer_details, payment_method):

    receipt = f"""

***Welcome to SETC Bus Booking System***


Route: {bus.bus_route}

From: {bus.sp}

To: {bus.ep}

Seats Booked: {', '.join(map(str, seat_numbers))}

Customer Name: {customer_name}

Gender: {customer_details[1]}

Age: {customer_details[2]}

Cost: Rs.{bus.cost_per_seat * len(seat_numbers)}

Payment Method: {payment_method}


***Thank You for Choosing Us!***

"""

    with open(f"receipt_{bus.bus_route}_{customer_name}.txt", "w") as file:

        file.write(receipt)

    print("Receipt downloaded.")

def main():

    buses = [

        Bus("SETC1", "Coimbatore", "Udumalpet", 60, 150),

        Bus("SETC2", "Pollachi", "Palani", 55, 120),

        Bus("SETC3", "Palani", "Madurai", 50, 180)

    ]

    while True:

        print("\n-----Menu-----\n1. View Buses\n2. Book Seats\n3. Exit")

        choice = input("Enter choice: ")

        if choice == '1':

            print("\nAvailable Routes:")

            for i, bus in enumerate(buses):

                print(f"{i + 1}. {bus}")

        elif choice == '2':

            print("\n***Welcome to SETC Bus Booking System***")

            bus_index = int(input("Choose bus number: ")) - 1

            if 0 <= bus_index < len(buses):

                seats_requested = int(input("How many seats do you want to book? : "))

                if seats_requested > 0:

                    booked_seats = []

                    for _ in range(seats_requested):

                        while True:

                            try:

                                seat_number = int(input(f"Enter desired seat number (1-{buses[bus_index].seats}): "))

                                if buses[bus_index].book_seat(seat_number):

                                    booked_seats.append(seat_number)

                                    break

                            except ValueError:

                                print("Invalid seat number. Please enter a number.")

                    if len(booked_seats) == seats_requested:

                        customer_details = get_customer_details()

                        payment_method = input("Enter payment method (Card/Cash): ").upper()

                        generate_receipt(buses[bus_index], booked_seats, customer_details[0], customer_details, payment_method)

                    else:

                        print("Seat booking failed.") 

                else:

                    print("Invalid number of seats.")

            else:

                print("Invalid bus number.")

        elif choice == '3':

            print("Thank you for using us!.")

            break

        else:

            print("Invalid choice. Please try again.")

if __name__ == "__main__":

    main()

OUTPUT:








ATM USING PYTHON

 CODE:

from datetime import datetime

import random

class ATM:

    def __init__(self, initial_balance):

        self.account_number = "ACC" + str(random.randint(1000000000, 9999999999))  # Generate 11-digit account number

        self.balance = initial_balance

        self.transaction_history = []

    def display_menu(self):

        print("\nWelcome to the ATM")

        print("1. Check Balance")

        print("2. Withdraw")

        print("3. Mini Statement")

        print("4. Exit")

    def check_balance(self):

        print(f"Your current balance is: {self.balance:.2f}") 

    def withdraw(self, amount):

        if amount > 0 and amount <= self.balance:

            old_balance = self.balance

            self.balance -= amount

            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

            self.transaction_history.append(f"[{current_time}] Withdrawal: -{amount:.2f} | Old Balance: {old_balance:.2f} | New Balance: {self.balance:.2f}") 

            return True  # Indicate successful withdrawal

        else:

            print("Insufficient funds.")

            return False

    def mini_statement(self):

        print("\n=== Mini Statement ===")

        print(f"Account Number: {self.account_number}")

        if not self.transaction_history:

            print("No recent transactions.")

        else:

            for transaction in self.transaction_history[-5:]: 

                print(transaction)

        print("======================")

def generate_withdrawal_receipt(amount, old_balance):

    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    print("\n--- Withdrawal Receipt ---")

    print(f"Date/Time: {current_time}")

    print(f"Withdrawal Amount: {amount:.2f}")

    print(f"Old Balance: {old_balance:.2f}")

    print(f"Current Balance: {old_balance - amount:.2f}")  # Calculate and display current balance

    print("-------------------------")

def validate_pin():

    """Validates the ATM PIN."""

    correct_pin = 3215  # Replace with your desired PIN

    attempts = 3

    while attempts > 0:

        entered_pin = int(input("Enter your ATM PIN: "))

        if entered_pin == correct_pin:

            print("PIN verified successfully.")

            return True

        else:

            attempts -= 1

            print(f"Incorrect PIN. {attempts} attempts remaining.")

    print("PIN verification failed. Exiting.")

    return False

if __name__ == "__main__":

    initial_balance = 50000  # Initial balance

    if validate_pin():

        atm = ATM(initial_balance) 

        while True:

            atm.display_menu()

            choice = int(input("Enter your choice: "))

            if choice == 1:

                atm.check_balance()

            elif choice == 2:

                withdrawal_amount = int(input("Enter the amount to withdraw: "))

                if atm.withdraw(withdrawal_amount):

                    generate_withdrawal_receipt(withdrawal_amount, atm.balance + withdrawal_amount) 

            elif choice == 3:

                atm.mini_statement()

            elif choice == 4:

                print("Thank you for using the ATM.")

                break

            else:

                print("Invalid choice. Please try again.")

OUTPUT:



















PETROL BUNK BILLING SYSTEM USING PYTHON

 CODE:


from datetime import datetime


def generate_bill():

    print("\n***WELCOME TO BHARAT PETROLEUM***\n")

    

    while True:

        print("\n***BILL***")

        customer_name = input("Enter customer name: ").strip()

        vehicle_no=input("Enter vehicle number:").strip()

        

        bill_no = f"hi{datetime.now().strftime('%d%m%y%H%M%S')}"

        date_time = datetime.now().strftime("%d-%m-%y %H:%M:%S")

        fuel_type = input("Enter fuel type (Petrol/Diesel): ").strip().capitalize()

        price_per_liter = float(input(f"Enter price per liter for {fuel_type}: "))

        quantity = float(input("Enter quantity in liters: "))

        

        total_cost = price_per_liter * quantity

        print("\n***Generating Bill***\n")

        print("*****BHARAT PETRILEUM *****")

        print(f"Bill No   : {bill_no}")

        print(f"Date/Time : {date_time}")

        print(f"Customer  : {customer_name}")

        print(f"Fuel Type : {fuel_type}")

        print(f"Quantity  : {quantity:.2f} liters")

        print(f"Price/Ltr : ₹{price_per_liter:.2f}")

        print(f"Total Cost: ₹{total_cost:.2f}")

        print("-----------------------")

        print("Thank you! Visit Again!")

        print("-----------------------\n")

        

        proceed = input("Do you want to process another transaction? (yes/no): ").strip().lower()

        if proceed != "yes":

            print("\n***THANKYOU.*** Goodbye!")

            break

if __name__ == "__main__":

    generate_bill()

OUTPUT:



CHATBOT USING TKINTER

  CODE : from tkinter import * # Create main window window = Tk() window.title("Healthcare Chatbot") window.geometry('600x600...