Python Tkinter Data Table Pagination

How to Create a Paginated Data Table in Python Tkinter

How to Create a Paginated Data Table in Python Tkinter




In this Python Tutorial we will see How to Create a Table in Python Tkinter with advanced pagination, navigation controls, and professional styling.


What We're Building ?

We're creating a sophisticated data table with:

- Dynamic pagination with customizable page sizes (5, 10, 15, 20 rows).
- Smart navigation controls with first/last/previous/next buttons.
- Page number buttons with intelligent ellipsis handling.
- Jump-to-page functionality with input validation.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter (GUI).
- VS Editor.






Project Source Code:




import tkinter as tk
from tkinter import ttk
import random
from typing import List, Tuple
import math

class PaginatedTable(tk.Tk):

def __init__(self):

super().__init__()

# Define color scheme for the application
self.primary_color = "#4F46e5"
self.hover_color = "#c7d2fe"
self.bg_color = "#f9fafb"
self.text_color = "#111827"

# Initialize pagination-related variables
# Start with first page
self.current_page = 1
# Number of rows to show per page
self.records_per_page = 5
# List to store all table data
self.all_data: List[Tuple] = []

self.setup_window()
self.create_styles()
self.initialize_components()
self.load_simple_data()
self.update_table()
self.center_window()


def setup_window(self):
self.title("Paginated Table")
self.geometry("900x620")
self.configure(bg=self.bg_color)
def center_window(self):
# Update window's actual dimensions
self.update_idletasks()
# Get window dimensions
width = self.winfo_width()
height = self.winfo_height()
# Calculate position to center window
x = (self.winfo_screenwidth() // 2) - (width // 2)
y = ((self.winfo_screenheight()-20) // 2) - (height // 2)
print(self.winfo_screenheight())
print(height)
# Set window position
self.geometry(f'{width}x{height}+{x}+{y}')
def initialize_components(self):
# Create main container frame
self.main_frame = tk.Frame(self, bg=self.bg_color, padx=20, pady=20)
self.main_frame.pack(fill=tk.BOTH, expand=True)

# Create white container for table
self.table_container = tk.Frame(self.main_frame, bg="white",
bd=1, relief="solid")
self.table_container.pack(fill=tk.BOTH, expand=True)

# Define table columns
columns = ("ID", "Name", "Email", "Status")

# Create table widget
self.table = ttk.Treeview(self.table_container, columns = columns,
show="headings", style="Modern.Treeview", selectmode="browse")

# Configure each column in table
for col in columns:
self.table.heading(col, text = col, anchor = "w")
self.table.column(col, anchor="w", width=100)
# Add vertical scrollbar
scrollbar = ttk.Scrollbar(self.table_container, orien="vertical",
command=self.table.yview)
self.table.configure(yscrollcommand=scrollbar.set)

# Arrange table and scrollbar
self.table.pack(side="left", fill="both", expand="True")
scrollbar.pack(side="right", fill="y")

# Create frame for pagination controls
self.pagination_frame = tk.Frame(self.main_frame, bg="white", height=60)
self.pagination_frame.pack(fill="x", pady=(20, 0))

# Create left section with page size selector
left_frame = tk.Frame(self.pagination_frame, bg="white")
left_frame.pack(side="left", padx=10)

# Create dropdown for selecting number of rows per page
self.page_size_var = tk.StringVar(value = "5 rows")
page_sizes = ["5 rows", "10 rows", "15 rows", "20 rows"]
self.page_size_combo = ttk.Combobox(left_frame, values = page_sizes,
textvariable = self.page_size_var,
style="Modern.TCombobox", width=10)
self.page_size_combo.pack(side="left", padx=5)
self.page_size_combo.bind('<<ComboboxSelected>>', self.on_page_size_change)

# Create label showing total records
self.total_records_label = tk.Label(left_frame, text="Total: 0 records",
bg="white", fg=self.text_color, font=("Arial", 11))
self.total_records_label.pack(side="left", padx=10)

# Create center frame for page navigation
self.center_frame = tk.Frame(self.pagination_frame, bg="white")
self.center_frame.pack(side="left", expand="True")

# Create right section for page jump
right_frame = tk.Frame(self.pagination_frame, bg = "white")
right_frame.pack(side="right", padx=10)

# Add "Go to page" label
tk.Label(right_frame, text="Go to page: ", bg="white", fg=self.text_color,
font=("Arial", 11)).pack(side="left")
# Create entry field for jumping to specific page
self.page_jump = tk.Entry(right_frame, width=5, font=("Arial", 11))
self.page_jump.pack(side="left", padx=5)
self.page_jump.bind("<Return>", self.on_page_jump)




def create_styles(self):
# Create style object for themed widgets
style = ttk.Style()
style.theme_use("clam")

# Configure style for table (Treeview)
style.configure("Modern.Treeview", background="white",
foreground=self.text_color, rowheight=50, fieldbackground = "white",
borderwidth = 0, font = ("Arial", 11))


# Configure style for table header (Treeview)
style.configure("Modern.Treeview.Heading", background="black",
foreground="white", borderwidth = 0, font = ("Inter", 11, 'bold'))

# Configure table selection colors
style.map("Modern.Treeview", background = [('selected', self.hover_color)],
foreground = [('selected', "red")])

# Configure style for dropdown (Combobox)
style.configure("Modern.TCombobox", background="white",
foreground=self.text_color, arrowcolor = "red")




def load_simple_data(self):
# Define possible status values
statuses = ["Active", "Pending", "Completed", "Inactive"]
self.all_data = []

# Generate 1000 sample records
for i in range(1, 1000):
self.all_data.append(
(f"#{i:03d}",
f"User{i}",
f"user{i}@example.com",
random.choice(statuses))
)
# Calculate total pages needed
self.total_pages = math.ceil(len(self.all_data) / self.records_per_page)



def create_pagination_button(self, parent, text, command, is_active = False):
# Create a button for pagination navigation
btn = tk.Button(parent, text = text, font=("Arial", 11),
bg = self.primary_color if is_active else "white",
fg = "white" if is_active else self.text_color,
bd = 1 if not is_active else 0,
relief = "solid" if not is_active else "flat",
width=3, height = 1, command=command)
btn.pack(side="left", padx = 2)
return btn


def update_table(self):
# Remove all existing rows
for item in self.table.get_children():
self.table.delete(item)
# Calculate which records to show
start = (self.current_page - 1) * self.records_per_page
end = start + self.records_per_page

# Add records for current page
for row in self.all_data[start: end]:
self.table.insert("", "end", values = row)

# Update pagination buttons
self.update_pagination()


def go_to_page(self, page):
# Change page if requested page is valid
if 1 <= page <= self.total_pages:
self.current_page = page
self.update_table()

def on_page_size_change(self, event):
# Get selected number of rows per page
size = int(self.page_size_var.get().split()[0])
# Update pagination settings
self.records_per_page = size
self.total_pages = math.ceil(len(self.all_data) / self.records_per_page)
self.current_page = 1
# Refresh table display
self.update_table()

def on_page_jump(self, event):
try:
# Try to convert entered page number to integer
page = int(self.page_jump.get())

# Go to page if number is valid
if 1 <= page <= self.total_pages:
self.go_to_page(page)

# Clear the entry field
self.page_jump.delete(0, tk.END)
except ValueError:
pass

def update_pagination(self):
# Clear existing pagination buttons
for widget in self.center_frame.winfo_children():
widget.destroy()

# Add first page button
self.create_pagination_button(self.center_frame, "⟪",
lambda: self.go_to_page(1), False)
# Add previous page button
self.create_pagination_button(self.center_frame, "←",
lambda: self.go_to_page(self.current_page - 1), False)

# Calculate which page numbers to show
start = max(1, self.current_page - 2)
end = min(self.total_pages, start + 4)

# Add ellipsis if needed at start
if start > 1:
tk.Label(self.center_frame, text = "...", bg="white").pack(side="left",
padx = 5)

# Add page number buttons
for i in range(start, end + 1):
self.create_pagination_button(self.center_frame, str(i),
lambda x = i: self.go_to_page(x),
i == self.current_page)

# Add ellipsis if needed at end
if end < self.total_pages:
tk.Label(self.center_frame, text = "...", bg="white").pack(side="left",
padx = 5)

# Add next page button
self.create_pagination_button(self.center_frame, "→",
lambda: self.go_to_page(self.current_page + 1), False)

# Add last page button
self.create_pagination_button(self.center_frame, "⟫",
lambda: self.go_to_page(self.total_pages), False)

# Update total records counter
self.total_records_label.config(text = f"Total: {len(self.all_data)} records")


if __name__ == "__main__":
app = PaginatedTable()
app.mainloop()



The Final Result:

Python Tkinter Data Table Pagination









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: