Condition Tree Builder for Streamlit
Streamlit-condition-tree is a custom Streamlit component that enables users to construct complex, nested condition trees, primarily for filtering DataFrames or building database queries. The library is currently at version 0.3.0, released in October 2024, and maintains an active development status with regular updates and improvements.
Warnings
- gotcha In version 0.3.0, the default value for the `always_show_buttons` parameter was changed to `True`. This may alter the visual presentation of the component, showing rule addition/deletion buttons even when not hovered.
- gotcha Version 0.2.0 introduced the capability to inject custom JavaScript code into the component's configuration. While powerful, this feature requires careful handling to avoid security vulnerabilities or unexpected rendering issues.
- gotcha When using Streamlit custom components, especially with `st.session_state`, ensure proper management of component keys. If a `key` is not used or updated correctly, the component might not re-render with new configurations or maintain its state across user interactions as expected.
- gotcha To save and load a condition tree's state, you must use the `key` parameter to store the tree in `st.session_state`. The saved tree (a dictionary) can then be passed back into the `condition_tree` component via its `tree` parameter to pre-populate it with previous conditions.
Install
-
pip install streamlit-condition-tree
Imports
- condition_tree
from streamlit_condition_tree import condition_tree
- config_from_dataframe
from streamlit_condition_tree import config_from_dataframe
Quickstart
import streamlit as st
import pandas as pd
from streamlit_condition_tree import condition_tree, config_from_dataframe
st.set_page_config(layout="wide")
st.title("Streamlit Condition Tree Demo")
# Initial dataframe
df = pd.DataFrame({
'First Name': ['Georges', 'Alfred', 'Maria', 'Sophie'],
'Age': [45, 98, 30, 25],
'Favorite Color': ['Green', 'Red', 'Blue', 'Green'],
'Like Tomatoes': [True, False, True, True]
})
st.subheader("Original DataFrame")
st.dataframe(df)
# Basic field configuration from dataframe
config = config_from_dataframe(df)
# Condition tree component
query_string = condition_tree(
config,
always_show_buttons=True,
placeholder="Build your filter conditions here..."
)
st.subheader("Generated Query String")
st.code(query_string)
# Filtered dataframe
if query_string:
try:
filtered_df = df.query(query_string)
st.subheader("Filtered DataFrame")
st.dataframe(filtered_df)
except Exception as e:
st.error(f"Error applying query: {e}")
else:
st.info("No conditions applied yet. Displaying original DataFrame.")