Skip to main content

Create Buttons and Actions in Streamlit

Create Buttons and Actions in Streamlit

The st.button() function in Streamlit is used to create interactive buttons in your application. By using buttons, you can trigger actions when they are clicked, enabling dynamic interactions with your app’s users.


1. Creating a Simple Button

To create a simple button, you can pass a label to st.button(). The button will be displayed, and when clicked, it will return a boolean value indicating whether it was pressed.

import streamlit as st
if st.button("Click Me"):
    st.write("Button clicked!")

Here’s an example demonstrating how to create a simple button that triggers an action:

if st.button("Start Process"):
    st.write("Process Started!")

2. Using Multiple Buttons

You can create multiple buttons in your application. Each button can trigger different actions depending on which one is clicked, making the interface interactive and user-friendly.

if st.button("Option 1"):
    st.write("Option 1 selected")

if st.button("Option 2"):
    st.write("Option 2 selected")

3. Triggering Multiple Actions with Buttons

Buttons can be used to trigger multiple actions in the same function. For example, you can combine different button clicks with other elements like displaying data or triggering API calls.

if st.button("Load Data"):
    st.write("Loading data...") 
    # Add data loading code here

if st.button("Analyze Data"):
    st.write("Analyzing data...") 
    # Add analysis code here

This demonstrates how to trigger multiple actions with different buttons:

  • Use one button to load data.
  • Use another button to analyze the loaded data.

4. Using Button State to Control Flow

You can also use the state of a button (whether it’s pressed or not) to control the flow of your application. This is useful for creating interactive workflows.

start_button = st.button("Start Process")
if start_button:
    st.write("Process has started!")
else:
    st.write("Click to start the process.") 

Example

import streamlit as st

if st.button("Start Process"):
    st.write("Process Started!")

if st.button("Load Data"):
    st.write("Data is loading...") 

if st.button("Analyze Data"):
    st.write("Data is being analyzed...")

Output:


Conclusion

The st.button() function is an essential tool for adding interactivity to your Streamlit applications. By creating buttons and triggering actions based on button clicks, you can build highly dynamic and engaging user interfaces that respond in real-time to user input.

Comments