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 :





CHATBOT USING TKINTER

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