Widget not working after adding key parameter

Hello,

I have a shared function that is used by multiple pages. When the widget doesn’t have key defined, Streamlit generates error about multiple widgets using the same autogenerated key and when I add the key parameter to widget, it stops working.

Has anyone has idea how to solve this issue?

Below is the code for the function.

import streamlit as st
import pandas as pd
from dblib import split_frame
import random

def sort_df_top_menu(df):
    select_rand_key = random.random()
    if len(df) > 0:
        top_menu = st.columns([.11,.78,.11])
    with top_menu[0]:
        sort = st.radio("Sort Data", options=["Yes", "No"], horizontal=1, index=1)
    if sort == "Yes":
        with top_menu[1]:
            sort_field = st.multiselect("Sort By", options=df.columns)
        with top_menu[2]:
            sort_direction = st.radio(
                "Sort Direction", options=["⬆️", "⬇️"], horizontal=True
            )
        df = df.sort_values(
            by=sort_field, ascending=sort_direction == "⬆️", ignore_index=True
        )
    return df

The call to this function is below from multiple pages.

data_df = sort_df_top_menu(data_df)

This is how the widget after adding the key parameter.
REC-20250311183155

This is how the widget is when key parameter is removed.
REC-20250311183443

Hello,

I see that you’re using select_rand_key = random.random() to generate a key. The key is supposed to be unique and persistent across reruns of the app. However, since random.random() generates a new value each time the app reloads, the key will keep changing, causing issues with Streamlit’s widget state.

Generating a random key can be a valid approach, but only if it remains consistent across reruns. One way to handle this would be:

  • If the key doesn’t exist, generate and store it.
  • Otherwise, reuse the existing key.

That said, I wouldn’t recommend using a random key in this case. Instead, you should define the key explicitly for each instance of the function. This ensures that multiple instances of the function can exist without conflicting widget keys.

        def sort_df_top_menu(df,key):

            if len(df) > 0:
                top_menu = st.columns([.11, .78, .11])
            with top_menu[0]:
                sort = st.radio("Sort Data", options=["Yes", "No"], horizontal=1, index=1)
            if sort == "Yes":
                with top_menu[1]:
                    sort_field = st.multiselect("Sort By", options=df.columns,key=f"{key}_multiselect")
                with top_menu[2]:
                    sort_direction = st.radio(
                        "Sort Direction", options=["⬆️", "⬇️"], horizontal=True, key=f"{key}_radio"
                    )
                df = df.sort_values(
                    by=sort_field, ascending=sort_direction == "⬆️", ignore_index=True
                )
            return df

        data = {
            "Name": ["Alice", "Bob", "Charlie", "David", "Eve"],
            "Age": [25, 30, 22, 35, 28],
            "Score": [random.randint(50, 100) for _ in range(5)],
            "Poneys": ["Bob", "Bobby", "Booba", "Dylan", "Boo"]
        }

        data_df = sort_df_top_menu(pd.DataFrame(data), key="DATA_the_one_with_poneys")

1 Like

Thank you for your help @Faltawer . Really appreciate it. This resolved the issue I was having.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.