Affichage des articles dont le libellé est pagination. Afficher tous les articles
Affichage des articles dont le libellé est pagination. Afficher tous les articles

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









JavaScript - Create Pagination Button For HTML Table

How to Add Pagination to HTML Tables Using JavaScript


JavaScript Create Pagination Button For HTML Table



In this Javascript tutorial, we will see how to create pagination buttons for HTML table with JavaScript. 
This JavaScript code adds pagination functionality to a table of product data, allowing users to navigate through multiple pages of data. It dynamically generates page navigation buttons and shows the relevant rows based on the selected page.



Project Source Code:



<!DOCTYPE html>
<html>
<head>
<title>Pagination</title>
<style>
table{width: 25%; border: 1px solid #555}

table tr{border: 1px solid #555}

table td{border: 1px solid #555}

.page-nav{background-color: yellowgreen; width: 25%; display: flex;
flex-wrap: wrap; justify-content: center}

.page-nav button{background-color: #333; color: #fff;}

.page-nav button:hover{background-color: rgb(119, 16, 16); color: #fff;
cursor: pointer;}

</style>
</head>
<body>
<table id="table">
<thead>
<tr>
<th>Product</th>
<th>Stock</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>Product 1</td>
<td>10</td>
<td>$11</td>
</tr>
<tr>
<td>Product 2</td>
<td>20</td>
<td>$331</td>
</tr>
<tr>
<td>Product 3</td>
<td>25</td>
<td>$14</td>
</tr>
<tr>
<td>Product 4</td>
<td>99</td>
<td>$73</td>
</tr>
<tr>
<td>Product 5</td>
<td>14</td>
<td>$30</td>
</tr>
<tr>
<td>Product 6</td>
<td>44</td>
<td>$22</td>
</tr>
<tr>
<td>Product 7</td>
<td>77</td>
<td>$33</td>
</tr>
<tr>
<td>Product 8</td>
<td>57</td>
<td>$62</td>
</tr>
<tr>
<td>Product 9</td>
<td>76</td>
<td>$59</td>
</tr>
<tr>
<td>Product 10</td>
<td>27</td>
<td>$42</td>
</tr>
<tr>
<td>Product 11</td>
<td>151</td>
<td>$36</td>
</tr>
<tr>
<td>Product 12</td>
<td>96</td>
<td>$80</td>
</tr>
<tr>
<td>Product 13</td>
<td>85</td>
<td>$32</td>
</tr>
<tr>
<td>Product 14</td>
<td>35</td>
<td>$75</td>
</tr>
</tbody>
</table>


<script>

// select the table and its rows
const table = document.getElementById('table');
const rows = table.querySelectorAll('tbody tr');

// set the number of rows per page and initialize the current page to 1
const rowsPerPage = 5;
let currentPage = 1;

// create a new div to hold the page navigation buttons
const pageNav = document.createElement('div');
pageNav.classList.add('page-nav');
table.parentNode.insertBefore(pageNav, table.nextSibling);


// function to show the rows of the current page
const showPage = (page)=>{
// set the current page to the one specified
currentPage = page;

// calculate the start and end indexes of the rows to display
const startIndex = (page - 1) * rowsPerPage;
const endIndex = startIndex + rowsPerPage;

// hide all rows
for(let i = 0; i < rows.length; i++){
rows[i].style.display = "none";
}

// display the rows within the selected range
for(let i = startIndex; i < endIndex; i++){
if(rows[i]){
rows[i].style.display = "table-row";
}
}

// update the current page button
const buttons = document.querySelectorAll(".page-nav button");
for(let i = 0; i < buttons.length; i++){
buttons[i].classList.remove("current-page");
}
// if the table is not empty
if(rows.length > 0)
{
document.querySelector(`#page-${currentPage}`).classList.add("current-page");
}

}


// function to create the page buttons
const createPageButtons = () => {
// calculate the total number of pages
const pages = Math.ceil(rows.length / rowsPerPage);
// create a button for each page
for(let i = 1; i <= pages; i++)
{
const button = document.createElement("button");
// set the ID of the button to "page-x", where x is the page number
button.id = `page-${i}`;
// set the button text to the page number
button.textContent = i;
// set the class of the first button to "current-page"
if(i === 1)
{
button.classList.add("current-page");
}
// add an event listener to the button that calls showPage()
// with the corresponding page number
button.addEventListener("click",() => {
showPage(i);
});
// append the button to the page navigation div
pageNav.appendChild(button);
}
}

// call createPageButtons() to create the initial set of page buttons
createPageButtons();
// call showPage() with an argument of 1 to display the first page of rows
showPage(1);

</script>

</body>
</html>






Code Explanation:

this JavaScript code, allows users to create a table with pagination.

This JavaScript code performs the following actions:

1 - Select Table Rows: Choose the table with the ID "table" and select all its rows in the tbody.

2 - Pagination Setup: Specify the number of rows per page (rowsPerPage) and start on page 1.

3 - Create Page Navigation: Generate a new <div> for page navigation buttons below the table. 
Define a function to make these buttons.

4 - Show Page Function: Create a function to show rows for the current page. 
Calculate start and end indexes. 
Hide all rows and show the selected range. 
Update the "current-page" class for the navigation button.

5 - Generate Page Buttons: Calculate total pages based on rows and rows per page. 
Make buttons for each page. 
Set button IDs to "page-x," where x is the page number. 
Add event listeners to call showPage for each page. 
Append buttons to the navigation div.



OUTPUT:





How To Create a Pagination In Html Table Using Footable

FooTable : How To Make Data Pagination In Html Table

________________________________________________________


In this FooTable Tutorial we will see How To Navigate Html Table Data With Pagination Using FooTable .

I Use In This Tutorial:
-FooTable.
-Php.
- NetBeans IDE .
- XAMPP .
- PhpMyAdmin .





Source Code:

<!-- php code to get data from mysql database -->

<?php

$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "test_db";

$connect = mysqli_connect($hostname, $username, $password, $databaseName);
$query = "SELECT * FROM `users";
$result = mysqli_query($connect, $query);

?>

<!DOCTYPE html>
<html>
    <head>
        <title> Html Table Pagination Using FooTable </title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="css/footable.core.css">
        <link rel="stylesheet" href="css/footable.metro.css">
        <script src="js/jquery-1.11.3.min.js"></script>
        <script src="js/footable.js"></script>
        <script src="js/footable.paginate.js"></script>     
  </head>
    <body>
        
     <!-- data-page-size = number of data to display -->
     <!-- data-XXX-text = text to display in the pagination bar -->
        <table class="footable" data-page-size="6" data-first-text="FIRST" data-next-text="NEXT" data-previous-text="PREVIOUS" data-last-text="LAST">
            <thead>
            <tr>
                <th>Id</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Age</th>
            </tr>
            </thead>

            <tbody>

                <!-- populate table from mysql database -->
            <?php while($row1 = mysqli_fetch_array($result)):;?>
            <tr>
                <td><?php echo $row1[0];?></td>
                <td><?php echo $row1[1];?></td>
                <td><?php echo $row1[2];?></td>
                <td><?php echo $row1[3];?></td>
            </tr>
            <?php endwhile;?>

            </tbody>

            <!-- the pagination -->
            <!-- hide-if-no-paging = hide the pagination control -->
            <tfoot class="hide-if-no-paging">
            <td colspan="5">
                <div class="pagination"></div>
            </td>
            </tfoot>
        </table>
    </body>
    <script type="text/javascript">
       
       $(document).ready(function(){
           
           $('.footable').footable();
           
       });
       
    </script>
</html>



///////////////OUTPUT: 




                                                           
                                                               
html table pagination
FooTable Pagination



                     
Demo From fooplugins :
Pagination

Other FooTable Tutorials :
Download And Use
Sorting Html Table
Responsive Html Table
Search And Filter Data In Html Table