Java Calculator With Mechanical Keyboard Buttons

How to Create a Calculator With Mechanical Keyboard Buttons in Java Netbeans

How to Create a Calculator With Mechanical Keyboard Buttons in Java Netbeans


In this Java Tutorial we will see How To Create a Calculator With Mechanical Keyboard Look and engaging click animations In Java Using Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:



/**
 *
 * @author 1BestCsharp
 */
public class Calculator3D extends JPanel{
    
    // These variables store the calculator's current state
    private String displayText = "0";           // Text shown on calculator screen
    private boolean startNewInput = true;       // Whether the next digit starts a new number
    private String operation = null;            // Current math operation (+, -, *, /)
    private double firstOperand = 0;            // First number in the calculation
    private final int MAX_DISPLAY_LENGTH = 12;  // Maximum number of digits on display
    
    // Colors used for different parts of the calculator
    private final Color buttonColor = new Color(0, 200, 255);         // Regular button color (blue)
    private final Color operatorButtonColor = new Color(255, 100, 255); // Math operator buttons color (pink)
    private final Color equalButtonColor = new Color(100, 255, 100);    // Equals button color (green)
    private final Color displayBgColor = new Color(15, 15, 26);         // Calculator screen background (dark)
    private final Color displayTextColor = new Color(240, 240, 240);    // Calculator screen text (light)
    
    // Button size and spacing measurements
    private final int buttonWidth = 60;   // Width of each button
    private final int buttonHeight = 50;  // Height of each button
    private final int buttonDepth = 15;   // How "deep" the 3D effect looks
    private final int gap = 10;           // Space between buttons
    
    // Layout of all calculator buttons in a grid
    private final String[][] buttonLabels = {
        {"7", "8", "9", "/"},    // First row of buttons
        {"4", "5", "6", "*"},    // Second row of buttons
        {"1", "2", "3", "-"},    // Third row of buttons
        {"0", ".", "C", "+"},    // Fourth row of buttons
        {"", "", "", "="}        // Fifth row (only equals button)
    };
    
    // Variables for button click animation
    private String clickedButton = null;  // Currently clicked button (if any)
    private javax.swing.Timer clickTimer;             // Timer to control how long click effect lasts
    private final int CLICK_DURATION = 150; // Click effect duration in milliseconds
    
    // Map to store button positions for detecting clicks
    private final Map<String, Rectangle> buttonBounds = new HashMap<>();
    
    
    public Calculator3D(){
        
        // Set calculator size and background color
        setPreferredSize(new Dimension(320, 420));
        setBackground(new Color(30, 30, 40));
        
        // Create timer that removes click effect after a short time
        clickTimer = new javax.swing.Timer(CLICK_DURATION, e -> {
            
            clickedButton = null;  // Clear the clicked button
            repaint();             // Redraw the calculator
            clickTimer.stop();     // Stop the timer until next click
            
        });
        
        // Listen for mouse clicks on the calculator
        addMouseListener(new MouseAdapter() {
            
           @Override
            public void mousePressed(MouseEvent e) {
                // When user clicks, check which button was pressed
                handleMousePress(e.getX(), e.getY());
            }
            
        });
        
    }
    
    @Override
    protected void paintComponent(Graphics g){
        
         super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        
         // Make lines and edges look smoother
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, 
                RenderingHints.VALUE_STROKE_PURE);
        
        // Draw calculator screen at the top
        drawDisplay(g2d);
        
        // Draw all calculator buttons below the screen
        drawButtons(g2d);
        
        
    }
    
    
    // Method to draw the calculator's display screen
    private void drawDisplay(Graphics2D g2d){
       
         // Set the size and position of the display screen
        int displayHeight = 70;
        int margin = 20;
        Rectangle2D display = new Rectangle2D.Double(
                margin, margin, getWidth() - 2 * margin, displayHeight);
        
                
        // Fill the display with background color
        g2d.setColor(displayBgColor);
        g2d.fill(display);
        
        // Draw border around the display
        g2d.setStroke(new BasicStroke(2f));
        g2d.setColor(new Color(100, 100, 120));
        g2d.draw(display);
        
        // Add shadow effect under the display
        g2d.setColor(new Color(0, 0, 0, 50));
        g2d.fillRect(margin + 3, margin + displayHeight, 
                getWidth() - 2 * margin, 5);
        
         // Display the calculator's current number (right-aligned)
        g2d.setFont(new Font("Monospaced", Font.BOLD, 30));
        g2d.setColor(displayTextColor);
        
        // Get text measurements to align properly
        FontMetrics fm = g2d.getFontMetrics();
        String textToDisplay = displayText;
        
        // If text is too long, show only the last digits
        if (textToDisplay.length() > MAX_DISPLAY_LENGTH) {
            textToDisplay = textToDisplay.substring(textToDisplay.length() - MAX_DISPLAY_LENGTH);
        }
        
        // Calculate position to right-align the text
        int textWidth = fm.stringWidth(textToDisplay);
        int textX = (getWidth() - margin - 10) - textWidth;
        int textY = margin + displayHeight - 20;
        
        // Draw the text on screen
        g2d.drawString(textToDisplay, textX, textY);
        
    }
    
    // Method to draw all calculator buttons
    private void drawButtons(Graphics2D g2d){
        
        // Starting position for the button grid
        int startX = 20;
        int startY = 110;
        
        // Clear previous button positions
        buttonBounds.clear();
        
         // Loop through each row and column in the button grid
         for(int row = 0; row < buttonLabels.length; row++){
             
             for(int col = 0; col < buttonLabels[row].length; col++){
                 
                String label = buttonLabels[row][col];
                if (label.isEmpty()) continue;  // Skip empty slots
                
                // Calculate button position
                int x = startX + col * (buttonWidth + gap);
                int y = startY + row * (buttonHeight + gap);
                
                // Store button position for detecting clicks later
                buttonBounds.put(label, new Rectangle(x, y, buttonWidth, buttonHeight));
                
                // Choose color based on button type
                Color buttonBaseColor;
                
                if (label.equals("=")) {
                    buttonBaseColor = equalButtonColor;  // Green for equals
                }
                else if ("+-*/C".contains(label)) {
                    buttonBaseColor = operatorButtonColor;  // Pink for operators
                }
                else {
                    buttonBaseColor = buttonColor;  // Blue for numbers
                }
         
                // Check if this button is currently being clicked
                boolean isClicked = label.equals(clickedButton);
                
                 // Draw this button with 3D effect
                draw3DButton(
                        g2d, 
                        x, 
                        y, 
                        buttonWidth, 
                        buttonHeight, 
                        buttonDepth, 
                        label, 
                        buttonBaseColor,
                        isClicked
                );
                 
             }
             
         }
        
    }
    
    
        // Method to draw a single 3D button
    private void draw3DButton(Graphics2D g2d, int x, int y, int width, int height, 
                             int depth, String label, Color color, boolean isClicked){
        
        // Save current drawing settings
        var originalTransform = g2d.getTransform();
        
        // When clicked, button appears pressed down
        int actualDepth = isClicked ? depth / 3 : depth;
        int yOffset = isClicked ? depth - actualDepth : 0;
        
        // Draw top face of button (main face)
        Color topColor = isClicked ? darken(color, 0.9) : color;
        g2d.setColor(topColor);
        Rectangle2D topFace = new Rectangle2D.Double(x, y + yOffset, width, height);
        g2d.fill(topFace);
        
        // Draw right face of button (side)
        Color rightColor = darken(color, 0.7);
        g2d.setColor(rightColor);
        Path2D rightFace = new Path2D.Double();
        
        rightFace.moveTo(x + width, y + yOffset);
        rightFace.lineTo(x + width + actualDepth, y + yOffset + actualDepth);
        
        rightFace.lineTo(x + width + actualDepth, y + yOffset + height + actualDepth);
        rightFace.lineTo(x + width, y + yOffset + height);
        
        rightFace.closePath();
        g2d.fill(rightFace);
        
        // Draw bottom face of button (bottom edge)
        Color bottomColor = darken(color, 0.5);
        g2d.setColor(bottomColor);
        Path2D bottomFace = new Path2D.Double();
        
        bottomFace.moveTo(x, y + yOffset + height);
        bottomFace.lineTo(x + width, y + yOffset + height);
        
        bottomFace.lineTo(x + width + actualDepth, y + yOffset + height + actualDepth);
        bottomFace.lineTo(x + actualDepth, y + yOffset + height + actualDepth);
        
        bottomFace.closePath();
        g2d.fill(bottomFace);
        
        // Draw black outlines around button faces
        g2d.setColor(Color.BLACK);
        g2d.setStroke(new BasicStroke(1.0f));
        g2d.draw(topFace);
        g2d.draw(rightFace);
        g2d.draw(bottomFace);
        
         // Draw the button's text (number or symbol)
        g2d.setColor(Color.BLACK);
        g2d.setFont(new Font("SansSerif", Font.BOLD, 20));
        
        FontMetrics fm = g2d.getFontMetrics();
        int textWidth = fm.stringWidth(label);
        int textHeight = fm.getHeight();
        
        g2d.drawString(label, 
                x + (width - textWidth) / 2, 
                y + yOffset + (height + textHeight / 2) / 2);
        
        // Restore original drawing settings
        g2d.setTransform(originalTransform);
        
    }
    
    // Handle mouse click at specific coordinates
    private void handleMousePress(int mouseX, int mouseY) {
        
        // Check all buttons to see if click was inside any of them
        for (Map.Entry<String, Rectangle> entry : buttonBounds.entrySet()) {
            
             if (entry.getValue().contains(mouseX, mouseY)) {
                 
                String label = entry.getKey();
                
                // Set clicked button for animation effect
                clickedButton = label;
                repaint();
                                                
                // Start or restart click animation timer
                if (clickTimer.isRunning()) {
                    clickTimer.restart();
                } else {
                    clickTimer.start();
                }
                
                // Handle the button's action
                processButtonPress(label);
                return;
                 
             }
            
        }
        
    }
    
    
    // Process a button click based on its label
    private void processButtonPress(String buttonLabel){
        
        // Clear button (resets calculator)
        if (buttonLabel.equals("C")) {
            displayText = "0";
            startNewInput = true;
            operation = null;
            firstOperand = 0;
            repaint();
            return;
        }
        
        // Number buttons (0-9)
        if ("0123456789".contains(buttonLabel)) {
            
            if (startNewInput) {
                
                // Start a new number
                displayText = buttonLabel;
                startNewInput = false;
                
            } else if (displayText.length() < MAX_DISPLAY_LENGTH) {
                // Add digit to existing number
                if (displayText.equals("0")) {
                    displayText = buttonLabel;  // Replace leading zero
                } else {
                    displayText += buttonLabel;  // Append digit
                }
            }
            
            repaint();
            return;
            
        }
        
         // Decimal point button
         if (buttonLabel.equals(".")) {
             
             if (startNewInput) {
                // Start a new decimal number
                displayText = "0.";
                startNewInput = false;
            }  else if (!displayText.contains(".") && displayText.length() < MAX_DISPLAY_LENGTH) {
                // Add decimal point if not already present
                displayText += ".";
            }
             
            repaint();
            return;
             
         }
         
         // Operation buttons (+, -, *, /)
         if ("+-*/".contains(buttonLabel)) {
             
            // Save current number and operation for later
            firstOperand = Double.parseDouble(displayText);
            operation = buttonLabel;
            startNewInput = true;
            
            repaint();
            return;
             
         }
         
         // Equals button (performs calculation)
         if (buttonLabel.equals("=") && operation != null) {
             
            // Get second number for calculation
            double secondOperand = Double.parseDouble(displayText);
            double result = 0;
            
            // Perform calculation based on operation
            switch (operation) {
                 case "+":
                    result = firstOperand + secondOperand;
                    break;
                 case "-":
                    result = firstOperand - secondOperand;
                    break;
                 case "*":
                    result = firstOperand * secondOperand;
                    break;
                 case "/":
                      if (secondOperand != 0) {
                        result = firstOperand / secondOperand;
                    }  else {
                        // Prevent division by zero
                        displayText = "Error";
                        startNewInput = true;
                        operation = null;
                        repaint();
                        return;
                    }
                     break;
            }
            
            // Format the result for display
            if (result == (long) result) {
                // Show whole number without decimal
                displayText = String.valueOf((long) result);
            }  else {
                
                 // Show decimal number
                displayText = String.valueOf(result);
                
                 // Truncate if too long
                if (displayText.length() > MAX_DISPLAY_LENGTH) {
                    
                   try {
                        // Round to reasonable precision
                        displayText = String.valueOf(Math.round(result * 1e10) / 1e10);
                    } catch (Exception e) {
                        displayText = "Error";
                    }
                    
                }
                
            }
            
            // Reset for next calculation
            startNewInput = true;
            operation = null;
            repaint();
             
         }
        
    }
    
    
    // Helper method to make a color darker
    private Color darken(Color color, double factor) {
        
        return new Color(
            Math.max((int)(color.getRed() * factor), 0),
            Math.max((int)(color.getGreen() * factor), 0),
            Math.max((int)(color.getBlue() * factor), 0)
        );
        
    }
    

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
         // Create window for calculator
         JFrame frame = new JFrame("Calculator");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.add(new Calculator3D());
         frame.pack();
         frame.setLocationRelativeTo(null);  // Center on screen
         frame.setVisible(true);  // Show the calculator
        
    }

}


  


The Final Result:

Java Calculator With Mechanical Keyboard Buttons

Java Mechanical Keyboard Calculator



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








 More Java Projects: 



Python To-Do List Project Source Code

How to Create To Do List Project In Python Tkinter


How to Create To Do List Project In Python Tkinter



In this Python Tutorial we will see How To Create a To Do List Project in Python using Tkinter.
This application provides a modern interface for managing tasks, allowing users to add, view, delete tasks, and Complete/Completed toggle button .

What We Are Gonna Use In This Project:

- Python Tkinter: GUI framework.
- Visual Studio Editor.





Project Source Code:



     - Build the user interface

Calculates screen dimensions and positions the application window at the center of the user's display.


def center_window(self):
"""Center the window on the screen."""
# Get screen dimensions
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()

# Calculate position
x = (screen_width - 900) // 2
y = (screen_height - 600) // 2

# Set window position
self.root.geometry(f"900x600+{x}+{y}")



     - Custom Window

Creates a custom title bar with application branding and window controls, replacing the default system title bar.


def setup_title_bar(self):
"""Create custom title bar with controls."""
self.title_bar = tk.Frame(self.root, bg=self.special_color, height=40)
self.title_bar.pack(fill=tk.X)

# Application title
title = tk.Label(self.title_bar, text="Tasks Manager",
font=self.title_font,
bg=self.special_color, fg="white")
title.pack(side=tk.LEFT, padx=15)

# Window controls container
controls = tk.Frame(self.title_bar, bg=self.special_color)
controls.pack(side=tk.RIGHT, padx=5)

# Control buttons
buttons = [
("□", lambda: self.toggle_maximize(), "#64748b"),
("x", lambda: self.root.destroy(), "#ef4444")
]

for symbol, command, hover_color, in buttons:
btn = tk.Label(controls, text=symbol, bg=self.special_color,
fg="white", font=self.title_font, padx=10)
btn.pack(side=tk.LEFT)
# Hover effects
btn.bind("<Enter>", lambda e,
color=hover_color: e.widget.configure(bg=color))
btn.bind("<Leave>", lambda e: e.widget.configure(bg=self.special_color))
btn.bind("<Button-1>", lambda e, cmd=command: cmd())



     - Window State Management

Toggles between maximized and normal window states when users click the maximize button.


def toggle_maximize(self):
"""Toggle between maximized and normal window state."""
if self.root.state() == 'zoomed':
self.root.state('normal')

else:
self.root.state('zoomed')



     - Bottom Control Panel

Creates the bottom action bar containing the primary "Add New Task" button with hover animations.


def setup_action_bar(self):
"""Create the bottom action bar with controls."""
action_bar = tk.Frame(self.root, bg=self.bg_color, height=60)
action_bar.pack(fill=tk.X, padx=20, pady=(0, 20))

# Add task button
add_btn = tk.Button(action_bar, text="+ Add New Task",
font=self.button_font, bg=self.special_color,
fg="white", border=0, padx=20, pady=10,
command=self.add_task, cursor="hand2")
add_btn.pack(side=tk.LEFT)

# Hover effect
add_btn.bind("<Enter>", lambda e: e.widget.configure(bg="#1d4ed8"))
add_btn.bind("<Leave>", lambda e: e.widget.configure(bg=self.special_color))



     - Drag Functionality Setup

Configures mouse event bindings to enable window dragging from the title bar.


def setup_window_drag(self):
"""Configure window dragging functionality."""
self.title_bar.bind("<Button-1>", self.on_drag_start)
self.title_bar.bind("<B1-Motion>", self.on_drag_motion)



     - Drag Initialization

Captures initial mouse coordinates when the user starts dragging the window.


def on_drag_start(self, event):
"""Store initial coordinates when starting drag."""
self.drag_data = (event.x_root - self.root.winfo_x(),
event.y_root - self.root.winfo_y())



     - Drag Position Updates

Continuously updates window position as the user drags the mouse across the screen.


def on_drag_motion(self, event):
"""Update window position during drag."""
x = event.x_root - self.drag_data[0]
y = event.y_root - self.drag_data[1]
self.root.geometry(f"+{x}+{y}")



     - Scrollable Content Area

Creates a scrollable canvas system for displaying task cards when content exceeds window height.


def setup_scrollable_canvas(self):
"""Create a scrollable canvas for task cards."""
# Create canvas with scrollbar
self.canvas =tk.Canvas(self.content_frame, bg=self.bg_color,
highlightthickness=0)
scrollbar = ttk.Scrollbar(self.content_frame, orient="vertical",
command=self.canvas.yview)
# Configure canvas scroll region
self.canvas.configure(yscrollcommand=scrollbar.set)
# Create frame for task cards
self.dashboard_panel = tk.Frame(self.canvas, bg=self.bg_color)

# Pack elements
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

# Create window in canvas for dashboard
self.canvas_window = self.canvas.create_window((0,0),
window=self.dashboard_panel, anchor="nw")

# Configure canvas scrolling
self.canvas.bind("<Configure>", self.on_canvas_configure)
self.dashboard_panel.bind("<Configure>", self.on_frame_configure)
self.canvas.bind_all("<MouseWheel>", self.on_mousewheel)



     - Canvas Resize Handler

Updates the canvas scroll region and content width when the canvas is resized.


def on_canvas_configure(self, event):
"""Update canvas scroll region when canvas is configured."""
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
width = event.width
self.canvas.itemconfig(self.canvas_window, width=width)



     - Frame Resize Handler

Recalculates scroll boundaries when the inner frame content changes size.


def on_frame_configure(self, event):
"""Update canvas scroll region when frame is configured."""
self.canvas.configure(scrollregion=self.canvas.bbox("all"))



     - Mouse Wheel Scrolling

Enables mouse wheel scrolling through the task list.


def on_mousewheel(self, event):
"""Handle mouse wheel scrolling."""
self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")



     - Task Creation

Handles new task creation with validation, modal dialog presentation, and task limit enforcement (12-task maximum limit).


def add_task(self):
"""Add a new task with modern dialog."""
if len(self.tasks) >= 12:
self.show_error("Maximum Tasks Reached",
                            "Please Complete Tasks Before Adding New Ones")
return
dialog = ModernInputDialog(self.root, "Add New Task", "Enter task details")
self.root.wait_window(dialog)

if dialog.result:
task = {
'text': dialog.result,
'date': datetime.now().strftime("%b %d, %Y"),
'status':'pending'
}
self.tasks.append(task)
self.update_task_panel()


     - UI Refresh

Rebuilds the entire task display panel, organizing tasks into horizontal tiers with proper spacing.


def update_task_panel(self):
"""Refresh the task display with styling."""
for widget in self.dashboard_panel.winfo_children():
widget.destroy()

for i, task in enumerate(self.tasks):
if i % self.tasks_per_tier == 0:
tier_frame = tk.Frame(self.dashboard_panel, bg = self.bg_color)
tier_frame.pack(fill = tk.X, pady = (10, 0))
self.create_task_card(tier_frame, task)



     - Individual Task UI

Generates individual task cards with completion status, action buttons, and custom styling.


def create_task_card(self, parent, task):
"""Create a task card with completion status."""
card = tk.Frame(parent, bg=self.card_bg, padx = 15, pady = 15,
highlightthickness = 1,
highlightbackground = "#e2eff0")
card.pack(side=tk.LEFT, padx = 10, pady = 10,
fill=tk.BOTH, expand=True)

header = tk.Frame(card, bg = self.card_bg)
header.pack(fill=tk.X, pady=(0, 10))

# Use completed font if task is marked as completed
task_font = self.completed_font if task.get('completed', False)
else self.text_font
task_label = tk.Label(header, text = task['text'],
font = task_font, bg = self.card_bg,
fg = self.text_color, wraplength = 200,
justify = tk.LEFT)
task_label.pack(side = tk.LEFT, anchor = "w")

tk.Label(card, text = task['date'], font = ("Helvatica", 9),
bg = self.card_bg, fg = "#64748b").pack(anchor="w")

btn_frame = tk.Frame(card, bg = self.card_bg)
btn_frame.pack(fill = tk.X, pady = (10, 0))

# Change complete button text based on completion status
complete_text = "✓ Completed" if task.get('completed', False)
else "✓ Complete"

complete_btn = tk.Button(btn_frame, text = complete_text,
font = self.button_font,
bg = "#22c55e" if not task.get('completed', False)
else "#64748b",
fg="white", border = 0, padx = 10, pady = 5,
command = lambda: self.toggle_complete_task(
task, task_label, complete_btn))

complete_btn.pack(side = tk.LEFT, padx = (0, 5))

delete_btn = tk.Button(btn_frame, text = "Delete",
font = self.button_font, bg = "#ef4444",
fg="white", border= 0, padx = 10, pady = 5,
command = lambda: self.delete_task(task))

delete_btn.pack(side = tk.LEFT)

for btn, hover_color in [(complete_btn, "#16a34a"), (delete_btn, "#dc2626")]:
btn.bind("<Enter>", lambda e,
color = hover_color: e.widget.configure(bg=color))
btn.bind("<Leave>", lambda e, btn = btn: self.reset_button_color(e, btn))



     - Task Status Management

Handles task completion toggling with success notifications.


def toggle_complete_task(self, task, label, button):
"""Toggle task completion status."""
task['completed'] = not task.get('completed', False)

if task['completed']:
label.configure(font = self.completed_font)
button.configure(text = "✓ Completed", bg="#64748b")
self.show_success("Task Completed", "Grate job completing your task !")
else:
label.configure(font = self.text_font)
button.configure(text = "✓ Complete", bg="#22c55e")



     - Hover State Management

Manages button color states after hover events end.


def reset_button_color(self, event, button):
"""Reset button color after hover."""
if "Complete" in button['text']:
if "Completed" in button['text']:
button.configure(bg = "#64748b")
else:
button.configure(bg = "#22c55e")
else:
button.configure(bg = "#ef4444")



     - Task Removal

Removes tasks from the data structure and triggers UI refresh.


def delete_task(self, task):
"""Remove a task and update display."""
self.tasks.remove(task)
self.update_task_panel()



     - User Notifications

Display system notifications for errors and successful actions using standard message boxes.


def show_error(self, title, message):
"""Display error message"""
messagebox.showerror(title, message)

def show_success(self, title, message):
"""Display error message"""
messagebox.showinfo(title, message)


     - ModernInputDialog Class - Custom Modal Dialog

Display system notifications for errors and successful actions using standard message boxes.


class ModernInputDialog(tk.Toplevel):
"""Custom modern dialog for task input."""
def __init__(self, parent, title, prompt):
super().__init__(parent)

self.result = None

# Configure dialog window
self.title(title)
self.geometry("400x250")
self.configure(bg="#ffffff")
self.resizable(False, False)
self.overrideredirect(True)
self.attributes('-alpha', 0.0)

self.center_on_parent(parent)

self.container = tk.Frame(self, bg="#ffffff",
highlightthickness=1,
highlightbackground="#e2e8f0",
padx=20, pady=20)
self.container.pack(fill=tk.BOTH, expand=True)

title_bar = tk.Frame(self.container, bg="#ffffff")
title_bar.pack(fill=tk.X, pady=(0, 15))

tk.Label(title_bar, text = title, font=("Helvatica", 14, "bold"),
bg="#ffffff",
fg="#1e293b").pack(side=tk.LEFT)

close_btn = tk.Label(title_bar, text = "×", font=("Helvetica", 14),
bg="#ffffff", fg="#64748b", cursor="hand2")
close_btn.pack(side=tk.RIGHT)
close_btn.bind("<Button-1>", lambda e: self.cancel())

tk.Label(self.container, text = prompt, font=("Helvetica", 11),
bg="#ffffff", fg="#1e293b").pack(fill=tk.X)
entry_frame = tk.Frame(self.container, bg="#f1f5f9",
highlightthickness=1,
highlightbackground="#e2e8f0")
entry_frame.pack(fill=tk.X, pady=(10, 20))

self.entry = tk.Entry(entry_frame, font=("Helvetica", 12),
bd=0, bg="#f1f5f9", fg="#1e2936",
insertbackground="#2563eb")
self.entry.pack(fill=tk.X, padx=10, pady=8)
self.entry.focus_set()

btn_frame = tk.Frame(self.container, bg="#ffffff")
btn_frame.pack(fill=tk.X, pady=(0, 10))

# Create modern styled buttons
buttons = [
("Cancel", "#f1f2f9", "#64748b", self.cancel),
("Add Task", "#2563eb", "#ffffff", self.submit)
]

for text, bg, fg, command in buttons:
btn = tk.Button(btn_frame, text=text, font=("Helvetica", 12),
bg=bg, fg=fg, bd=0, padx=20, pady=8, cursor="hand2",
command=command)
btn.pack(side=tk.RIGHT, padx=5)

# Add hover effects
if text == "cancel":
btn.bind("<Enter>", lambda e: e.widget.configure(bg="#e2e8f0"))
btn.bind("<Leave>", lambda e: e.widget.configure(bg="#f1f5f9"))
else:
btn.bind("<Enter>", lambda e: e.widget.configure(bg="#1d4ed8"))
btn.bind("<Leave>", lambda e: e.widget.configure(bg="#2563eb"))

# Add key bindings
self.bind("<Return>", lambda e: self.submit())
self.bind("<Escape>", lambda e: self.cancel())


# Make dialog draggable
title_bar.bind("<Button-1>", self.start_drag)
title_bar.bind("<B1-Motion>", self.drag)

# Fade in animation
self.fade_in()


def fade_in(self):
"""Animate the dialog fading in."""
alpha = self.attributes("-alpha")
if alpha < 1.0:
alpha += 0.1
self.attributes("-alpha", alpha)
self.after(20, self.fade_in)

def fade_out(self):
"""Animate the dialog fading out."""
alpha = self.attributes("-alpha")
if alpha > 0:
alpha -= 0.1
self.attributes("-alpha", alpha)
self.after(20, self.fade_out)
else:
self.destroy()

def submit(self):
"""Handle dialog submission with fade out animation."""
self.result = self.entry.get()
self.fade_out()

def cancel(self):
"""Handle dialog cancellation with fade out animation."""
self.fade_out()

def center_on_parent(self, parent):
"""Center the dialog window on its parent."""
# Get parent window position and size
parent_x = parent.winfo_x()
parent_y = parent.winfo_y()
parent_width = parent.winfo_width()
parent_height = parent.winfo_height()

# Calculate center position
x = parent_x + (parent_width - 400) // 2
y = parent_y + (parent_height - 250) // 2

# Set dialog position
self.geometry(f"400x250+{x}+{y}")


def start_drag(self, event):
"""Store initial coordinates for window dragging."""
self.drag_data = (event.x_root - self.winfo_x(), event.y_root - self.winfo_y())

def drag(self, event):
"""Update window position during drag."""
x = event.x_root - self.drag_data[0]
y = event.y_root - self.drag_data[1]
self.geometry(f"+{x}+{y}")






The Final Result:

Python To-Do List Project Source Code

Python To-Do List Project

Python To-Do List Project In Tkinter

To-Do List Project In Python Tkinter

To-Do List App In Python Tkinter

Tasks Project In Python Tkinter



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