Changing Dropdown/selectbox value based on action

Hey Team,
I have two dropdowns and both gets values from user. But when user takes swap actions I want the values in dropdowns to be swapped.

# Create a Streamlit app title
st.title("Language Translator App")

# Create three columns for layout
col1, col2, col3 = st.columns(3)

# Source Language Selection Component
with col1:
    source_lang = st.selectbox("Select Source Language", ["English", "French", "Spanish", "German", "Italian"])

# Target Language Selection Component
with col2:
    target_lang = st.selectbox("Select Target Language", ["English", "French", "Spanish", "German", "Italian"])

# Swap Language Button
with col3:
    if st.button("Swap Languages"):
        source_lang, target_lang = target_lang, source_lang

How will this work?

import streamlit as st

def language_picker(label, key):
    languages = ["English", "French", "Spanish", "German", "Italian"]
    st.selectbox(label, options=languages, key=key)

def swap():
    temp = st.session_state.source_lang
    st.session_state.source_lang = st.session_state.target_lang
    st.session_state.target_lang = temp

language_picker("Translate from", "source_lang")
language_picker("Translate to", "target_lang")

st.button("Swap", on_click=swap)

1 Like

Worked like magic. Thanks @mathcatsand

1 Like

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