How to use Tabulator on_click and selected_dataframe

On Discord (link) Cyb3rMonk asks how to use Tabulators on_click and selected_dataframe attributes?

My recommendation would be to translate the features to Parameters you can use with pn.bind, @pn.depends and pn.rx.

For example by creating a TabulatorExtension helper class like below.

import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import panel as pn
import param

pn.extension("tabulator")


class TabulatorExtension(param.Parameterized):
    value: pn.widgets.Tabulator = param.ClassSelector(
        class_=pn.widgets.Tabulator, allow_refs=False, constant=True
    )

    click_event = param.Parameter()
    selected_dataframe = param.DataFrame()

    def __init__(self, **params):
        super().__init__(**params)

        self.value.on_click(self._handle_click)

    def _handle_click(self, event):
        self.click_event = event

    @param.depends("value.selection", watch=True)
    def _handle_selection(self):
        self.selected_dataframe = self.value.selected_dataframe


timestamps = [datetime.now() - timedelta(minutes=5 * i) for i in range(10)]
messages = [
    "User logged in",
    "File uploaded",
    "Error: File not found",
    "User logged out",
    "Database connection established",
    "New user registration",
    "Password changed",
    "System update completed",
    "Email sent to user",
    "User password reset",
]
log_df = pd.DataFrame({"Timestamp": timestamps, "Message": messages})


table = pn.widgets.Tabulator(log_df)
extension = TabulatorExtension(value=table)

pn.Column(
    table, extension.param.click_event, extension.param.selected_dataframe
).servable()
1 Like

Thank you so much, Marc!
Iā€™m quite unfamiliar with param library. In the code you provided, did you modify an existing object/method or just created a custom one? Where should I start learning especially for these kinds of modifications/extensions?

1 Like

Hi @Mehmet

I reused the existing .on_click, .selection and .selected_dataframe methods.

What I did was to turn them into parameters that you can .bind to.

The best place to learn about parameters is in the Intermediate Tutorials

image

1 Like