Python Expenses And Incomes Tracker Using Tkinter

How To Make an Expenses And Incomes Tracker Project In Python Tkinter



In this Python tutorial we will see how to create a simple Expenses and Incomes Tracker application using the Tkinter library for the graphical user interface. 
The application allows users to track their expenses and incomes by adding transactions with specified types, amounts, and descriptions.
It provides a graphical user interface (GUI) for inputting transactions and displays a list of all transactions along with total expenses, total incomes, and the overall balance.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter for GUI.
- VS Code Editor.




Project Source Code:




import tkinter as tk
from tkinter import messagebox
from tkinter import ttk


class Transaction:
def __init__(self, transaction_type, amount, description):
self.transaction_type = transaction_type
self.amount = amount
self.description = description

class ExpensesIncomesTracker:
def __init__(self, root):
self.root = root
self.root.title("Expenses and Incomes Tracker")

# Initialize variables
self.transaction_var = tk.StringVar()
self.total_incomes = tk.DoubleVar()
self.total_expenses = tk.DoubleVar()
self.total_balance = tk.DoubleVar()
self.description = tk.StringVar()

# Create the UI
self.create_ui()

def create_ui(self):
# Create and pack the title label
titleLabel = ttk.Label(self.root, text="Expenses and Incomes Tracker",
        font=("Arial", 16, "bold"), foreground="#d35400")
titleLabel.pack(pady=10)

# Create and pack radio buttons for transaction type
transactionRadioFrame = ttk.Frame(self.root)
transactionRadioFrame.pack(pady=10)
expenseRadio = ttk.Radiobutton(transactionRadioFrame, text="Expense",
        variable=self.transaction_var, value="Expense")

incomeRadio = ttk.Radiobutton(transactionRadioFrame, text="Income",
        variable=self.transaction_var, value="Income")

expenseRadio.grid(row=0, column=0, padx=10)
incomeRadio.grid(row=0, column=1, padx=10)

# Create and pack the frame for amount and description
entryFrame = ttk.Frame(self.root)
entryFrame.pack(pady=10)

# Create amount label and entry
amountLabel = ttk.Label(entryFrame, text="Amount: ", font=("Arial", 12),
        foreground="#34495e")

amountLabel.grid(row=0,column=0, padx=5)

self.amountEntry = ttk.Entry(entryFrame, font=("Arial", 12))
self.amountEntry.grid(row=0,column=1)

# Create description label and entry
descriptionLabel = ttk.Label(entryFrame, text="Description: ",
        font=("Arial", 12), foreground="#34495e")

descriptionLabel.grid(row=0,column=2, padx=5)

self.descriptionEntry = ttk.Entry(entryFrame, font=("Arial", 12))
self.descriptionEntry.grid(row=0,column=3)

# Create and pack the "Add Transaction" button
addButton = tk.Button(self.root, text="Add Transaction", bg="yellow",
        fg="black", font=("Arial", 12, "bold"), width="22",
        command=self.add_transaction)

addButton.pack(pady=10)

# Create and pack the frame for the lists of expenses and incomes
listFrame = ttk.Frame(self.root)
listFrame.pack()

# Create Treeview with Scrollbar for expenses and incomes
self.expenses_incomes_list = ttk.Treeview(listFrame,
        columns=("Type", "Amount", "Description"), show="headings", height=5)

self.expenses_incomes_list.heading("Type", text="Type")
self.expenses_incomes_list.heading("Amount", text="Amount")
self.expenses_incomes_list.heading("Description", text="Description")
self.expenses_incomes_list.pack(side="right", padx=(0, 20), fill=tk.Y)

# Scrollbar for expenses and incomes Treeview
scrollbar = ttk.Scrollbar(listFrame, orient="vertical",
        command=self.expenses_incomes_list.yview)

scrollbar.pack(side="left", padx=(20, 0), fill="y")
self.expenses_incomes_list.config(yscrollcommand=scrollbar.set)

# Create and pack the frame for displaying totals
totalsFrame = ttk.Frame(self.root)
totalsFrame.pack(pady=10)

total_expenses_label = ttk.Label(totalsFrame, text="Total Expenses: ",
        font=("Arial", 12, "bold"), foreground="#e74c3c")

total_expenses_label.grid(row=0, column=0, padx=0)

self.total_expenses_display = ttk.Label(totalsFrame,
        textvariable=self.total_expenses, font=("Arial", 12, "bold"),
        foreground="#e74c3c")

self.total_expenses_display.grid(row=0, column=1, padx=(0,20))

total_incomes_label = ttk.Label(totalsFrame, text="Total Incomes: ",
        font=("Arial", 12, "bold"), foreground="#2ecc71")

total_incomes_label.grid(row=0, column=2, padx=0)

self.total_incomes_display = ttk.Label(totalsFrame,
        textvariable=self.total_incomes, font=("Arial", 12, "bold"),
        foreground="#2ecc71")

self.total_incomes_display.grid(row=0, column=3, padx=(0,20))

total_balance_label = ttk.Label(totalsFrame, text="Balance: ",
        font=("Arial", 12, "bold"), foreground="#3498db")

total_balance_label.grid(row=0, column=4, padx=0)

self.total_balance_display = ttk.Label(totalsFrame,
        textvariable=self.total_balance, font=("Arial", 12, "bold"),
        foreground="#3498db")

self.total_balance_display.grid(row=0, column=5, padx=(0,20))



def add_transaction(self):
# Get transaction type, amount, and description from the UI
transaction_type = self.transaction_var.get()
amount_entry_text = self.amountEntry.get()
description_entry_text = self.descriptionEntry.get()

try:
amount = float(amount_entry_text)
except ValueError:
self.show_error_message("Invalid amount. Please enter a numeric value.")
return

if not amount_entry_text or amount <= 0 :
self.show_error_message("Amount cannot be empty or non-positive")
return

if not transaction_type :
self.show_error_message("Please select a transaction type")
return


# Create a Transaction object and update UI
transaction = Transaction(transaction_type, amount_entry_text,
        description_entry_text)

self.expenses_incomes_list.insert("","end", values=(transaction_type,
        amount_entry_text, description_entry_text))

if transaction_type == "Expense":
self.total_expenses.set(self.total_expenses.get() + amount)

else:
self.total_incomes.set(self.total_incomes.get() + amount)

self.total_balance.set(self.total_incomes.get() - self.total_expenses.get())

# Clear entries
self.amountEntry.delete(0, "end")
self.descriptionEntry.delete(0, "end")


def show_error_message(self, message):
tk.messagebox.showerror("Error", message)




if __name__ == "__main__":
root = tk.Tk()
app = ExpensesIncomesTracker(root)
root.mainloop()



The Final Result:




if you want the source code click on the download button below









Java Create Pie / Donut Chart

How to Create a Custom Pie and Donut Chart In Java Netbeans



In this Java Tutorial we will see How To Create a Custom Pie Chart from scratch using graphics class in java netbeans.
We Will also see how to create a donut chart.
Each chart has three slices is drawn based on the percentage data provided with custom colors (yellow, blue, green) .

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code For The Pie Chart:


package piechart;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author 1BestCsharp
 */
public class PieChart extends JFrame {
    
    private PieChartPanel pieChartPanel;
    
    public PieChart(){
        setTitle("Pie Chart");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(550,400);
        setLocationRelativeTo(null);
        
        pieChartPanel = new PieChartPanel();
        pieChartPanel.setBackground(Color.white);
        add(pieChartPanel);
        setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        new PieChart();
        
    }
   
}


// Panel class for displaying the pie chart
class PieChartPanel extends JPanel
{
    // Custom slice colors for the pie chart    
    private Color[] sliceColors = {Color.decode("#FEC107"),
                                   Color.decode("#2196F3"),
                                   Color.decode("#4CAF50")
                                  };
    // Initial data values representing percentages
    private int[] data = {40, 30, 30};
    
    // Override the paintComponent method to customize the drawing of the panel
    @Override
    protected void paintComponent(Graphics g){
        
        super.paintComponent(g);
        // Call the method to draw the pie chart
        drawPieChart(g);
        
    }
    
    // Method to draw the pie chart
    private void drawPieChart(Graphics g){
        // Create a Graphics2D object
        Graphics2D g2d = (Graphics2D) g;
        // Get the width of the panel
        int width = getWidth();
        // Get the height of the panel
        int height = getHeight();
        // Determine the diameter of the pie chart
        int diameter = Math.min(width, height) - 20;
        // Calculate the x-coordinate for the pie chart
        int x = (width - diameter) / 2;
        // Calculate the y-coordinate for the pie chart
        int y = (height - diameter) / 2;
        // Initialize the starting angle for the first slice of the pie chart
        int startAngle = 0;
        
        for(int i = 0; i < data.length; i++){
            // Calculate the arc angle for the current slice
            int arcAngle = (int) ((double) data[i] / 100 * 360);
            // Set the color for the current slice
            g2d.setColor(sliceColors[i]);
            // Fill the arc representing the slice
            g2d.fillArc(x, y, diameter, diameter, startAngle, arcAngle);
            // Update the starting angle for the next slice
            startAngle += arcAngle;
        }
        
        // Draw labels or legends for each slice
        // Set the x-coordinate for the legend
        int legendX = width - 110;
        // Set the initial y-coordinate for the legend
        int legendY = 20;
        
        for(int i = 0; i < data.length; i++)
        {
            // Set the color for the legend box
            g2d.setColor(sliceColors[i]);
            // Fill the legend box with color
            g2d.fillRect(legendX, legendY, 20, 20);
            // Set the text color for the legend
            g2d.setColor(Color.black);
            // Draw the legend text with slice number and percentage
            g2d.drawString("Slice " + (i + 1) + ": " + data[i] + "%", legendX + 30, legendY + 15);
            // Update the y-coordinate for the next legend entry
            legendY += 30;
        }
        
    }
    
}




   

Project Source Code For The Donut Chart:


package piechart;


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author 1BestCsharp
 */
public class DonutChart extends JFrame {
    
    private DonutChartPanel donutChartPanel;
    
    public DonutChart(){
        setTitle("Donut Chart");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(550,400);
        setLocationRelativeTo(null);
        
        donutChartPanel = new DonutChartPanel();
        donutChartPanel.setBackground(Color.white);
        add(donutChartPanel);
        setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        new DonutChart();
        
    }
   
}


// Panel class for displaying the pie chart
class DonutChartPanel extends JPanel
{
    //private Color[] sliceColors = {Color.decode("#3498db"), Color.decode("#e74c3c"), Color.decode("#2ecc71")}; // Modern slice colors
    //private Color[] sliceColors = {Color.decode("#FF6B6B"), Color.decode("#74B9FF"), Color.decode("#55E6C1")}; // Custom slice colors
    private Color[] sliceColors = {Color.decode("#FF5733"), Color.decode("#33FFB2"), Color.decode("#3360FF")}; // Updated colors
    
    
    // Custom slice colors for the pie chart    
    /*private Color[] silceColors = {Color.decode("#FEC107"),
                                   Color.decode("#2196F3"),
                                   Color.decode("#4CAF50")
                                  };
*/
    // Initial data values representing percentages
    private int[] data = {75, 20, 5};
    
    // Override the paintComponent method to customize the drawing of the panel
    @Override
    protected void paintComponent(Graphics g){
        
        super.paintComponent(g);
        // Call the method to draw the pie chart
        drawDonutChart(g);
        
    }
    
    // Method to draw the pie chart
    private void drawDonutChart(Graphics g){
        // Create a Graphics2D object
        Graphics2D g2d = (Graphics2D) g;
        // Get the width of the panel
        int width = getWidth();
        // Get the height of the panel
        int height = getHeight();
        // Determine the diameter of the pie chart
        int outerDiameter = Math.min(width, height) - 20;
        int innerDiameter = outerDiameter / 2;
        // Calculate the x-coordinate for the pie chart
        int x = (width - outerDiameter) / 2;
        // Calculate the y-coordinate for the pie chart
        int y = (height - outerDiameter) / 2;
        // Initialize the starting angle for the first slice of the pie chart
        int startAngle = 0;
        
        for(int i = 0; i < data.length; i++){
            // Calculate the arc angle for the current slice
            int arcAngle = (int) ((double) data[i] / 100 * 360);
            // Set the color for the current slice
            g2d.setColor(sliceColors[i]);
            // Fill the arc representing the slice
            g2d.fillArc(x, y, outerDiameter, outerDiameter, startAngle, arcAngle);
            g2d.setColor(getBackground());
            g2d.fillArc(x+(outerDiameter - innerDiameter) / 2, y + (outerDiameter - innerDiameter) / 2, innerDiameter, innerDiameter, 0, 360);
            // Update the starting angle for the next slice
            startAngle += arcAngle;
        }
        
        // Draw labels or legends for each slice
        // Set the x-coordinate for the legend
        int legendX = width - 110;
        // Set the initial y-coordinate for the legend
        int legendY = 20;
        
        for(int i = 0; i < data.length; i++)
        {
            // Set the color for the legend box
            g2d.setColor(sliceColors[i]);
            // Fill the legend box with color
            g2d.fillRect(legendX, legendY, 20, 20);
            // Set the text color for the legend
            g2d.setColor(Color.black);
            // Draw the legend text with slice number and percentage
            g2d.drawString("Slice " + (i + 1) + ": " + data[i] + "%", legendX + 30, legendY + 15);
            // Update the y-coordinate for the next legend entry
            legendY += 30;
        }
        
    }
    
}



    



if you want the source code click on the download button below













Python Analog Clock Using Tkinter

How to Create Analog Clock In Python Tkinter

Python Analog Clock Using Tkinter



In this Python tutorial we will create an analog clock application using the Tkinter library for the graphical user interface. 
The clock displays an animated face with hour, minute, and second hands that update every second to reflect the current time.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter for GUI.
- VS Code Editor.




Project Source Code:



import tkinter as tk
from datetime import datetime
import math

class AnalogClockApp:

def __init__(self,root):
# Initialize the Tkinter window
self.root = root
self.root.title("Analog Clock")
# Create a canvas for drawing the clock
self.canvas = tk.Canvas(self.root, width=300,height=300,bg="white")
self.canvas.pack()

# Delay the initial drawing
self.root.after(100, self.draw_clock)


def draw_clock(self):

# Clear the canvas
self.canvas.delete("all")

# Get the width and height of the canvas
width = self.canvas.winfo_width()
height = self.canvas.winfo_height()

# Calculate the center coordinates of the canvas
center_x = width // 2
center_y = height // 2

# Draw clock face, numbers, and hands
clock_radius = min(width, height) // 2 - 10
self.canvas.create_oval(center_x - clock_radius,
center_y - clock_radius,
center_x + clock_radius,
center_y + clock_radius,
outline = "orange", width = 5)

# Draw clock numbers
for i in range(1, 13):
# Calculate the angle for positioning each number around the clock face
angle = math.radians(360 / 12 * (i - 3))
# Calculate the x-coordinate of the number position
# based on the clock radius and angle
num_x = center_x + int(clock_radius * 0.8 * math.cos(angle))
# Calculate the y-coordinate of the number position
# based on the clock radius and angle
num_y = center_y + int(clock_radius * 0.8 * math.sin(angle))
# Create a text element to display the number at the calculated position
self.canvas.create_text(num_x, num_y, text=str(i),
font=("Helvetica", 12, "bold"))

# Get current time
current_time = datetime.now()
# Calculate the angle for the hour hand based on the current hour
hours_angle = math.radians(360 / 12 * (current_time.hour % 12 - 3))
# Calculate the angle for the minute hand based on the current minute
minutes_angle = math.radians(360 / 60 * (current_time.minute - 15))
# Calculate the angle for the second hand based on the current second
seconds_angle = math.radians(360 / 60 * (current_time.second - 15))

# Set the length of the hour hand
hour_hand_length = clock_radius * 0.5
# Set the length of the minute hand
minute_hand_length = clock_radius * 0.7
# Set the length of the second hand
second_hand_length = clock_radius * 0.9

# Calculate the x-coordinate of the hour hand
hour_hand_x = center_x + int(hour_hand_length * math.cos(
hours_angle))
# Calculate the y-coordinate of the hour hand
hour_hand_y = center_y + int(hour_hand_length * math.sin(
hours_angle))
# Draw the hour hand
self.canvas.create_line(center_x, center_y, hour_hand_x,
hour_hand_y, fill="#333", width=6)

# Calculate the x-coordinate of the minute hand
minute_hand_x = center_x + int(minute_hand_length * math.cos(
minutes_angle))
# Calculate the y-coordinate of the minute hand
minute_hand_y = center_y + int(minute_hand_length * math.sin(
minutes_angle))
# Draw the minute hand
self.canvas.create_line(center_x, center_y, minute_hand_x,
minute_hand_y, fill="#3498db", width=4)

# Calculate the x-coordinate of the second hand
second_hand_x = center_x + int(second_hand_length * math.cos(
seconds_angle))
# Calculate the y-coordinate of the second hand
second_hand_y = center_y + int(second_hand_length * math.sin(
seconds_angle))
# Draw the second hand
self.canvas.create_line(center_x, center_y, second_hand_x,
second_hand_y, fill="#e74c32", width=2)

# Update the clock every second
# Schedule the draw_clock method to be called after 1000 milliseconds
self.root.after(1000, self.draw_clock)



if __name__ == "__main__":
root = tk.Tk()
app = AnalogClockApp(root)
root.mainloop()



The Final Result:

Analog Clock Using Python Tkinter