Path: blob/main/doc/how_to/custom_components/python/create_custom_widget.md
2012 views
Build a Widget in Python
In this guide we will demonstrate how to create a custom widget that enables users to select a list of features and set their values entirely in Python.
We will leverage the PyComponent
class to construct this custom widget. The PyComponent
allows us to combine multiple Panel components into a more complex and functional widget. The resulting class will combine a MultiSelect
widget with a dynamic number of FloatInput
widgets.
Code Overview
Below is the complete implementation of the FeatureInput
custom widget:
This is a lot to take in so let us break it down into a few pieces:
Inheritance
The FeatureInput
class inherits from pn.custom.PyComponent
and pn.widgets.WidgetBase
. This multiple inheritance structure allows us to create custom components that behave one of the three core component types that Panel defines Widget
, Pane
and Panel
(i.e. a layout). You should always inherit from the component type base class first, i.e. WidgetBase
in this case and the component implementation class second, i.e. PyComponent
in this case.
Parameter Definitions
It defines the following parameters:
value
: A dictionary that stores the selected features and their corresponding values.features
: A dictionary of available features and their default values.selected_features
: The list of features that have been selected._selected_widgets
: A "private" column layout that contains the widgets for editing the selected features.
State handling
The two most important methods in configuring state are the constructor (__init__
) and the (__panel__
) method which will be invoked to create the component lazily at render time.
Constructor
In the __init__
method, we initialize the widget parameters and create a MultiChoice
widget for selecting features. We also set up a column to hold the selected feature widgets.
__panel__
PyComponent
classes must define a __panel__
method which tells Panel how the component should be rendered. Here we return a layout of the MultiSelect
and a column containing the selected features.
Syncing state
We use @param.depends
decorators to define methods that react to changes in the features
and selected_features
parameters:
_reset_selected_features
: Ensures that only available features are selected._handle_selected_features_change
: Updates the widgets and thevalue
parameter when the selected features change.
Widget Updates
The _update_value
method updates the value
parameter based on the current values of the feature widgets. The _update_selected_widgets
method creates and updates the widgets for the selected features.
Creating the Application
Now, let's create an application to demonstrate our custom FeatureInput
widget in action. We will define a set of features related to a wind turbine and use our widget to select and set their values: