filename
stringlengths 24
54
| content
stringlengths 819
44.7k
|
---|---|
st.select_slider_-_Streamlit_Docs.txt | st.select_slider - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets remove BUTTONS st.button st.download_button st.form_submit_button link st.link_button st.page_link SELECTIONS st.checkbox st.color_picker st.feedback st.multiselect st.pills st.radio st.segmented_control st.selectbox st.select_slider st.toggle NUMERIC st.number_input st.slider DATE & TIME st.date_input st.time_input TEXT st.chat_input link st.text_area st.text_input MEDIA & FILES st.audio_input st.camera_input st.data_editor link st.file_uploader Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Input widgets / st.select_slider st.select_slider Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a slider widget to select items from a list. This also allows you to render a range slider by passing a two-element tuple or list as the value . The difference between st.select_slider and st.slider is that select_slider accepts any datatype and takes an iterable set of options, while st.slider only accepts numerical or date/time data and takes a range as input. Function signature [source] st.select_slider(label, options=(), value=None, format_func=special_internal_function, key=None, help=None, on_change=None, args=None, kwargs=None, *, disabled=False, label_visibility="visible") Parameters label (str) A short label explaining to the user what this slider is for. The label can optionally contain GitHub-flavored Markdown of the following types: Bold, Italics, Strikethroughs, Inline Code, Links, and Images. Images display like icons, with a max height equal to the font height. Unsupported Markdown elements are unwrapped so only their children (text contents) render. Display unsupported elements as literal characters by backslash-escaping them. E.g., "1\. Not an ordered list" . See the body parameter of st.markdown for additional, supported Markdown directives. For accessibility reasons, you should never set an empty label, but you can hide it with label_visibility if needed. In the future, we may disallow empty labels by raising an exception. options (Iterable) Labels for the select options in an Iterable . This can be a list , set , or anything supported by st.dataframe . If options is dataframe-like, the first column will be used. Each label will be cast to str internally by default. value (a supported type or a tuple/list of supported types or None) The value of the slider when it first renders. If a tuple/list of two values is passed here, then a range slider with those lower and upper bounds is rendered. For example, if set to (1, 10) the slider will have a selectable range between 1 and 10. Defaults to first option. format_func (function) Function to modify the display of the labels from the options. argument. It receives the option as an argument and its output will be cast to str. key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. No two widgets may have the same key. help (str) An optional tooltip that gets displayed next to the widget label. Streamlit only displays the tooltip when label_visibility="visible" . on_change (callable) An optional callback invoked when this select_slider's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. disabled (bool) An optional boolean that disables the select slider if set to True . The default is False . label_visibility ("visible", "hidden", or "collapsed") The visibility of the label. The default is "visible" . If this is "hidden" , Streamlit displays an empty spacer instead of the label, which can help keep the widget alligned with other widgets. If this is "collapsed" , Streamlit displays no label or spacer. Returns (any value or tuple of any value) The current value of the slider widget. The return type will match the data type of the value parameter. Examples import streamlit as st color = st.select_slider( "Select a color of the rainbow", options=[ "red", "orange", "yellow", "green", "blue", "indigo", "violet", ], ) st.write("My favorite color is", color) And here's an example of a range select slider: import streamlit as st start_color, end_color = st.select_slider( "Select a range of color wavelength", options=[ "red", "orange", "yellow", "green", "blue", "indigo", "violet", ], value=("red", "blue"), ) st.write("You selected wavelengths between", start_color, "and", end_color) Built with Streamlit 🎈 Fullscreen open_in_new Featured videos Check out our video on how to use one of Streamlit's core functions, the select slider! 🎈 In the video below, we'll take it a step further and make a double-ended slider. Previous: st.selectbox Next: st.toggle forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.connections.BaseConnection_-_Streamlit_Docs.txt | st.connections.BaseConnection - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets remove SECRETS st.secrets secrets.toml CONNECTIONS st.connection SnowflakeConnection SQLConnection BaseConnection SnowparkConnection delete Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Connections and secrets / BaseConnection star Tip This page only contains information on the st.connections.BaseConnection class. For a deeper dive into creating and managing data connections within Streamlit apps, read Connecting to data . st.connections.BaseConnection Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake The abstract base class that all Streamlit Connections must inherit from. This base class provides connection authors with a standardized way to hook into the st.connection() factory function: connection authors are required to provide an implementation for the abstract method _connect in their subclasses. Additionally, it also provides a few methods/properties designed to make implementation of connections more convenient. See the docstrings for each of the methods of this class for more information Note While providing an implementation of _connect is technically all that's required to define a valid connection, connections should also provide the user with context-specific ways of interacting with the underlying connection object. For example, the first-party SQLConnection provides a query() method for reads and a session property for more complex operations. Class description [source] st.connections.BaseConnection(connection_name, **kwargs) Methods reset () Reset this connection so that it gets reinitialized the next time it's used. BaseConnection.reset Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Reset this connection so that it gets reinitialized the next time it's used. This method can be useful when a connection has become stale, an auth token has expired, or in similar scenarios where a broken connection might be fixed by reinitializing it. Note that some connection methods may already use reset() in their error handling code. Function signature [source] BaseConnection.reset() Returns (None) No description Example import streamlit as st conn = st.connection("my_conn") # Reset the connection before using it if it isn't healthy # Note: is_healthy() isn't a real method and is just shown for example here. if not conn.is_healthy(): conn.reset() # Do stuff with conn... Previous: SQLConnection Next: st.experimental_connection forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Annotate_an_Altair_chart_-_Streamlit_Docs.txt | Annotate an Altair chart - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements remove CHARTS Annotate an Altair chart DATAFRAMES Get dataframe row-selections Execution flow add Connect to data sources add Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Elements / Annotate an Altair chart Annotate an Altair chart Altair allows you to annotate your charts with text, images, and emojis. You can do this by overlaying two charts to create a layered chart . Applied concepts Use layered charts in Altair to create annotations. Prerequisites This tutorial requires the following Python libraries: streamlit altair>=4.0.0 vega_datasets This tutorial assumes you have a clean working directory called your-repository . You should have a basic understanding of the Vega-Altair charting library. Summary In this example, you will create a time-series chart to track the evolution of stock prices. The chart will have two layers: a data layer and an annotation layer. Each layer is an altair.Chart object. You will combine the two charts with the + opterator to create a layered chart. Within the data layer, you'll add a multi-line tooltip to show information about datapoints. To learn more about multi-line tooltips, see this example in Vega-Altair's documentation. You'll add another tooltip to the annotation layer. Here's a look at what you'll build: Complete code expand_more import streamlit as st import altair as alt import pandas as pd from vega_datasets import data @st.cache_data def get_data(): source = data.stocks() source = source[source.date.gt("2004-01-01")] return source stock_data = get_data() hover = alt.selection_single( fields=["date"], nearest=True, on="mouseover", empty="none", ) lines = ( alt.Chart(stock_data, title="Evolution of stock prices") .mark_line() .encode( x="date", y="price", color="symbol", ) ) points = lines.transform_filter(hover).mark_circle(size=65) tooltips = ( alt.Chart(stock_data) .mark_rule() .encode( x="yearmonthdate(date)", y="price", opacity=alt.condition(hover, alt.value(0.3), alt.value(0)), tooltip=[ alt.Tooltip("date", title="Date"), alt.Tooltip("price", title="Price (USD)"), ], ) .add_selection(hover) ) data_layer = lines + points + tooltips ANNOTATIONS = [ ("Sep 01, 2007", 450, "🙂", "Something's going well for GOOG & AAPL."), ("Nov 01, 2008", 220, "🙂", "The market is recovering."), ("Dec 01, 2007", 750, "😱", "Something's going wrong for GOOG & AAPL."), ("Dec 01, 2009", 680, "😱", "A hiccup for GOOG."), ] annotations_df = pd.DataFrame( ANNOTATIONS, columns=["date", "price", "marker", "description"] ) annotations_df.date = pd.to_datetime(annotations_df.date) annotation_layer = ( alt.Chart(annotations_df) .mark_text(size=20, dx=-10, dy=0, align="left") .encode(x="date:T", y=alt.Y("price:Q"), text="marker", tooltip="description") ) combined_chart = data_layer + annotation_layer st.altair_chart(combined_chart, use_container_width=True) Built with Streamlit 🎈 Fullscreen open_in_new Build the example Initialize your app In your_repository , create a file named app.py . In a terminal, change directories to your_repository and start your app. streamlit run app.py Your app will be blank since you still need to add code. In app.py , write the following: import streamlit as st import altair as alt import pandas as pd from vega_datasets import data You'll be using these libraries as follows: You'll download a dataset using vega_datasets . You'll maniputate the data using pandas . You'll define a chart using altair . Save your app.py file and view your running app. Click " Always rerun " or hit your " A " key in your running app. Your running preview will automatically update as you save changes to app.py . Your preview will still be blank. Return to your code. Build the data layer You'll build an interactive time-series chart of the stock prices with a multi-line tooltip. The x-axis represents the date, and the y-axis represents the stock price. Import data from vega_datasets . @st.cache_data def get_data(): source = data.stocks() source = source[source.date.gt("2004-01-01")] return source stock_data = get_data() The @st.cache_data decorator turns get_data() into a cahced function. Streamlit will only download the data once since the data will be saved in a cache. For more information about caching, see Caching overview . Define a mouseover selection event in Altair. hover = alt.selection_single( fields=["date"], nearest=True, on="mouseover", empty="none", ) This defines a mouseover selection for points. fields=["date"] allows Altair to identify other points with the same date. You will use this to create a vertical line highlight when a user hovers over a point. Define a basic line chart to graph the five series in your data set. lines = ( alt.Chart(stock_data, title="Evolution of stock prices") .mark_line() .encode( x="date", y="price", color="symbol", ) ) Draw points on the lines and highlight them based on the mouseover selection. points = lines.transform_filter(hover).mark_circle(size=65) Since the mouseover selection includes fields=["date"] , Altair will draw circles on each series at the same date. Draw a vertical rule at the location of the mouseover selection. tooltips = ( alt.Chart(stock_data) .mark_rule() .encode( x="yearmonthdate(date)", y="price", opacity=alt.condition(hover, alt.value(0.3), alt.value(0)), tooltip=[ alt.Tooltip("date", title="Date"), alt.Tooltip("price", title="Price (USD)"), ], ) .add_selection(hover) ) The opacity parameter ensures each vertical line is only visible when it's part of a mouseover selection. Each alt.Tooltip adds a line to your multi-line tooltip. Combine the lines, points, and tooltips into a single chart. data_layer = lines + points + tooltips Optional: Test out your code by rendering your data layer. st.altair_chart(data_layer, use_container_width=True) Save your file and examine the chart in your app. Use your mouse to hover over points. Observe the circle marks, vertical line, and tooltip as you hover over a point. Delete the line or keep it at the end of your app to be updated as you continue. Build the annotation layer Now that you have the first chart that shows the data, you can annotate it with text and an emoji. In this section, you'll add some emojis and tooltips to mark specifc points of interest. Create a list of annotations. ANNOTATIONS = [ ("Sep 01, 2007", 450, "🙂", "Something's going well for GOOG & AAPL."), ("Nov 01, 2008", 220, "🙂", "The market is recovering."), ("Dec 01, 2007", 750, "😱", "Something's going wrong for GOOG & AAPL."), ("Dec 01, 2009", 680, "😱", "A hiccup for GOOG."), ] annotations_df = pd.DataFrame( ANNOTATIONS, columns=["date", "price", "marker", "description"] ) annotations_df.date = pd.to_datetime(annotations_df.date) The first two columns ("date" and "price") determine where Altair will place the marker. The third column ("marker") determines what icon Altair will place. The last column ("description") will fill in the associated tooltip. Create a scatter plot with the x-axis representing the date and the y-axis representing the height ("price") of each annotation. annotation_layer = ( alt.Chart(annotations_df) .mark_text(size=20, dx=-10, dy=0, align="left") .encode(x="date:T", y=alt.Y("price:Q"), text="marker", tooltip="description") ) The dx=-10, dy=0 inside of .mark_text() offsets the icons so they are centered at the coordinate in your annotations dataframe. The four columns are passed to the chart through the .encode() method. If you want to use the same marker for all points, you can remove text="marker" from the .encode() method and add the marker to .mark_text() . For example, .mark_text(text="🥳") would make all the icons be "🥳". For more information about .mark_text() , see Altair's documentation . Combine the chart layers Define the combined chart. combined_chart = data_layer + annotation_layer Display the chart in Streamlit. st.altair_chart(combined_chart, use_container_width=True) Next steps Play around with your new app. If you want to use custom images instead of text or emojis to annotation your chart, you can replace the line containing .mark_text() with .mark_image() . For some URL string stored in a variable IMAGE_URL , you could do something like this: .mark_image( width=12, height=12, url=IMAGE_URL, ) If you want to enable panning and zooming for your chart, add .interactive() when you define your combined chart: combined_chart = (data_layer + annotation_layer).interactive() Previous: Elements Next: Get dataframe row-selections forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Build_LLM_apps_-_Streamlit_Docs.txt | Build LLM apps - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources add Multipage apps add Work with LLMs remove Build a basic LLM chat app Build an LLM app using LangChain Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Work with LLMs Build LLM apps Build a basic chat app Build a simple OpenAI chat app to get started with Streamlit's chat elements. Build an LLM app using LangChain Build a chat app using the LangChain framework with OpenAI. Previous: Multipage apps Next: Build a basic LLM chat app forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Execution_flow_-_Streamlit_Docs.txt | Execution flow - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow remove st.dialog st.form st.form_submit_button st.fragment st.rerun st.stop Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Execution flow Execution flow Change execution By default, Streamlit apps execute the script entirely, but we allow some functionality to handle control flow in your applications. Modal dialog Insert a modal dialog that can rerun independently from the rest of the script. @st.dialog("Sign up") def email_form(): name = st.text_input("Name") email = st.text_input("Email") Fragments Define a fragment to rerun independently from the rest of the script. @st.fragment(run_every="10s") def fragment(): df = get_data() st.line_chart(df) Rerun script Rerun the script immediately. st.rerun() Stop execution Stops execution immediately. st.stop() Group multiple widgets By default, Streamlit reruns your script everytime a user interacts with your app. However, sometimes it's a better user experience to wait until a group of related widgets is filled before actually rerunning the script. That's what st.form is for! Forms Create a form that batches elements together with a “Submit" button. with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Form submit button Display a form submit button. with st.form(key='my_form'): name = st.text_input("Name") email = st.text_input("Email") st.form_submit_button("Sign up") Third-party components These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras ! Autorefresh Force a refresh without tying up a script. Created by @kmcgrady . from streamlit_autorefresh import st_autorefresh st_autorefresh(interval=2000, limit=100, key="fizzbuzzcounter") Pydantic Auto-generate Streamlit UI from Pydantic Models and Dataclasses. Created by @lukasmasuch . import streamlit_pydantic as sp sp.pydantic_form(key="my_form", model=ExampleModel) Streamlit Pages An experimental version of Streamlit Multi-Page Apps. Created by @blackary . from st_pages import Page, show_pages, add_page_title show_pages([ Page("streamlit_app.py", "Home", "🏠"), Page("other_pages/page2.py", "Page 2", ":books:"), ]) Previous: Navigation and pages Next: st.dialog forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Connect_Streamlit_to_Supabase_-_Streamlit_Docs.txt | Connect Streamlit to Supabase - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources remove AWS S3 BigQuery Firestore open_in_new Google Cloud Storage Microsoft SQL Server MongoDB MySQL Neon PostgreSQL Private Google Sheet Public Google Sheet Snowflake Supabase Tableau TiDB TigerGraph Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Connect to data sources / Supabase Connect Streamlit to Supabase Introduction This guide explains how to securely access a Supabase instance from Streamlit Community Cloud. It uses st.connection , Streamlit Supabase Connector (a community-built connection developed by @SiddhantSadangi ) and Streamlit's Secrets management . Supabase is the open source Firebase alternative and is based on PostgreSQL. push_pin Note Community-built connections, such as the Streamlit Supabase Connector , extend and build on the st.connection interface and make it easier than ever to build Streamlit apps with a wide variety of data sources. These type of connections work exactly the same as the ones built into Streamlit and have access to all the same capabilities. Sign in to Supabase and create a project First, head over to Supabase and sign up for a free account using your GitHub. Sign in with GitHub Authorize Supabase Once you're signed in, you can create a project. Your Supabase account Create a new project Your screen should look like this once your project has been created: priority_high Important Make sure to note down your Project API Key and Project URL highlighted in the above screenshot. ☝️ You will need these to connect to your Supabase instance from Streamlit. Create a Supabase database Now that you have a project, you can create a database and populate it with some sample data. To do so, click on the SQL editor button on the same project page, followed by the New query button in the SQL editor. Open the SQL editor Create a new query In the SQL editor, enter the following queries to create a database and a table with some example values: CREATE TABLE mytable ( name varchar(80), pet varchar(80) ); INSERT INTO mytable VALUES ('Mary', 'dog'), ('John', 'cat'), ('Robert', 'bird'); Click Run to execute the queries. To verify that the queries were executed successfully, click on the Table Editor button on the left menu, followed by your newly created table mytable . Write and run your queries View your table in the Table Editor With your Supabase database created, you can now connect to it from Streamlit! Add Supabase Project URL and API key to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the SUPABASE_URL and SUPABASE_KEY here: # .streamlit/secrets.toml [connections.supabase] SUPABASE_URL = "xxxx" SUPABASE_KEY = "xxxx" Replace xxxx above with your Project URL and API key from Step 1 . priority_high Important Add this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets . Copy the content of secrets.toml into the text area. More information is available at Secrets management . Add st-supabase-connection to your requirements file Add the st-supabase-connection community-built connection library to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt st-supabase-connection==x.x.x star Tip We've used the st-supabase-connection library here in combination with st.connection to benefit from the ease of setting up the data connection, managing your credentials, and Streamlit's caching capabilities that native and community-built connections provide. You can however still directly use the Supabase Python Client Library library if you prefer, but you'll need to write more code to set up the connection and cache the results. See Using the Supabase Python Client Library below for an example. Write your Streamlit app Copy the code below to your Streamlit app and run it. # streamlit_app.py import streamlit as st from st_supabase_connection import SupabaseConnection # Initialize connection. conn = st.connection("supabase",type=SupabaseConnection) # Perform query. rows = conn.query("*", table="mytable", ttl="10m").execute() # Print results. for row in rows.data: st.write(f"{row['name']} has a :{row['pet']}:") See st.connection above? This handles secrets retrieval, setup, query caching and retries. By default, query() results are cached without expiring. In this case, we set ttl="10m" to ensure the query result is cached for no longer than 10 minutes. You can also set ttl=0 to disable caching. Learn more in Caching . If everything worked out (and you used the example table we created above), your app should look like this: As Supabase uses PostgresSQL under the hood, you can also connect to Supabase by using the connection string Supabase provides under Settings > Databases. From there, you can refer to the PostgresSQL tutorial to connect to your database. Using the Supabase Python Client Library If you prefer to use the Supabase Python Client Library directly, you can do so by following the steps below. Add your Supabase Project URL and API key to your local app secrets: Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the SUPABASE_URL and SUPABASE_KEY here: # .streamlit/secrets.toml SUPABASE_URL = "xxxx" SUPABASE_KEY = "xxxx" Add supabase to your requirements file: Add the supabase Python Client Library to your requirements.txt file, preferably pinning its version (replace x.x.x with the version you want installed): # requirements.txt supabase==x.x.x Write your Streamlit app: Copy the code below to your Streamlit app and run it. # streamlit_app.py import streamlit as st from supabase import create_client, Client # Initialize connection. # Uses st.cache_resource to only run once. @st.cache_resource def init_connection(): url = st.secrets["SUPABASE_URL"] key = st.secrets["SUPABASE_KEY"] return create_client(url, key) supabase = init_connection() # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(): return supabase.table("mytable").select("*").execute() rows = run_query() # Print results. for row in rows.data: st.write(f"{row['name']} has a :{row['pet']}:") See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data , it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching . Previous: Snowflake Next: Tableau forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Enabling_camera_or_microphone_access_in_your_brows.txt | Enabling camera or microphone access in your browser - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Knowledge base / FAQ / Enabling camera access in your browser Enabling camera or microphone access in your browser Streamlit apps may include a widget to upload images from your camera or record sound with your microphone. To safeguard the users' privacy and security, browsers require users to explicitly allow access to their camera or microphone before those devices can be used. To learn how to enable camera access, please check the documentation for your browser: Chrome Safari Firefox Previous: How do I create an anchor link? Next: How to download a file in Streamlit? forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Magic_-_Streamlit_Docs.txt | Magic - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic remove st.write st.write_stream magic Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Write and magic / magic Magic Magic commands are a feature in Streamlit that allows you to write almost anything (markdown, data, charts) without having to type an explicit command at all. Just put the thing you want to show on its own line of code, and it will appear in your app. Here's an example: # Draw a title and some text to the app: ''' # This is the document title This is some _markdown_. ''' import pandas as pd df = pd.DataFrame({'col1': [1,2,3]}) df # 👈 Draw the dataframe x = 10 'x', x # 👈 Draw the string 'x' and then the value of x # Also works with most supported chart types import matplotlib.pyplot as plt import numpy as np arr = np.random.normal(1, 1, size=100) fig, ax = plt.subplots() ax.hist(arr, bins=20) fig # 👈 Draw a Matplotlib chart How Magic works Any time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write (which you'll learn about later). Also, magic is smart enough to ignore docstrings. That is, it ignores the strings at the top of files and functions. If you prefer to call Streamlit commands more explicitly, you can always turn magic off in your ~/.streamlit/config.toml with the following setting: [runner] magicEnabled = false priority_high Important Right now, Magic only works in the main Python app file, not in imported files. See GitHub issue #288 for a discussion of the issues. Featured video Learn what the st.write and magic commands are and how to use them. Previous: st.write_stream Next: Text elements forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Button_behavior_and_examples_-_Streamlit_Docs.txt | Button behavior and examples - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts remove CORE Architecture & execution add Multipage apps add App design remove Animate & update elements Button behavior and examples Dataframes Using custom classes Working with timezones ADDITIONAL Connections and secrets add Custom components add Configuration and theming add App testing add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Concepts / App design / Button behavior and examples Button behavior and examples Summary Buttons created with st.button do not retain state. They return True on the script rerun resulting from their click and immediately return to False on the next script rerun. If a displayed element is nested inside if st.button('Click me'): , the element will be visible when the button is clicked and disappear as soon as the user takes their next action. This is because the script reruns and the button return value becomes False . In this guide, we will illustrate the use of buttons and explain common misconceptions. Read on to see a variety of examples that expand on st.button using st.session_state . Anti-patterns are included at the end. Go ahead and pull up your favorite code editor so you can streamlit run the examples as you read. Check out Streamlit's Basic concepts if you haven't run your own Streamlit scripts yet. When to use if st.button() When code is conditioned on a button's value, it will execute once in response to the button being clicked and not again (until the button is clicked again). Good to nest inside buttons: Transient messages that immediately disappear. Once-per-click processes that saves data to session state, a file, or a database. Bad to nest inside buttons: Displayed items that should persist as the user continues. Other widgets which cause the script to rerun when used. Processes that neither modify session state nor write to a file/database.* * This can be appropriate when disposable results are desired. If you have a "Validate" button, that could be a process conditioned directly on a button. It could be used to create an alert to say 'Valid' or 'Invalid' with no need to keep that info. Common logic with buttons Show a temporary message with a button If you want to give the user a quick button to check if an entry is valid, but not keep that check displayed as the user continues. In this example, a user can click a button to check if their animal string is in the animal_shelter list. When the user clicks " Check availability " they will see "We have that animal!" or "We don't have that animal." If they change the animal in st.text_input , the script reruns and the message disappears until they click " Check availability " again. import streamlit as st animal_shelter = ['cat', 'dog', 'rabbit', 'bird'] animal = st.text_input('Type an animal') if st.button('Check availability'): have_it = animal.lower() in animal_shelter 'We have that animal!' if have_it else 'We don\'t have that animal.' Note: The above example uses magic to render the message on the frontend. Stateful button If you want a clicked button to continue to be True , create a value in st.session_state and use the button to set that value to True in a callback. import streamlit as st if 'clicked' not in st.session_state: st.session_state.clicked = False def click_button(): st.session_state.clicked = True st.button('Click me', on_click=click_button) if st.session_state.clicked: # The message and nested widget will remain on the page st.write('Button clicked!') st.slider('Select a value') Toggle button If you want a button to work like a toggle switch, consider using st.checkbox . Otherwise, you can use a button with a callback function to reverse a boolean value saved in st.session_state . In this example, we use st.button to toggle another widget on and off. By displaying st.slider conditionally on a value in st.session_state , the user can interact with the slider without it disappearing. import streamlit as st if 'button' not in st.session_state: st.session_state.button = False def click_button(): st.session_state.button = not st.session_state.button st.button('Click me', on_click=click_button) if st.session_state.button: # The message and nested widget will remain on the page st.write('Button is on!') st.slider('Select a value') else: st.write('Button is off!') Alternatively, you can use the value in st.session_state on the slider's disabled parameter. import streamlit as st if 'button' not in st.session_state: st.session_state.button = False def click_button(): st.session_state.button = not st.session_state.button st.button('Click me', on_click=click_button) st.slider('Select a value', disabled=st.session_state.button) Buttons to continue or control stages of a process Another alternative to nesting content inside a button is to use a value in st.session_state that designates the "step" or "stage" of a process. In this example, we have four stages in our script: Before the user begins. User enters their name. User chooses a color. User gets a thank-you message. A button at the beginning advances the stage from 0 to 1. A button at the end resets the stage from 3 to 0. The other widgets used in stage 1 and 2 have callbacks to set the stage. If you have a process with dependant steps and want to keep previous stages visible, such a callback forces a user to retrace subsequent stages if they change an earlier widget. import streamlit as st if 'stage' not in st.session_state: st.session_state.stage = 0 def set_state(i): st.session_state.stage = i if st.session_state.stage == 0: st.button('Begin', on_click=set_state, args=[1]) if st.session_state.stage >= 1: name = st.text_input('Name', on_change=set_state, args=[2]) if st.session_state.stage >= 2: st.write(f'Hello {name}!') color = st.selectbox( 'Pick a Color', [None, 'red', 'orange', 'green', 'blue', 'violet'], on_change=set_state, args=[3] ) if color is None: set_state(2) if st.session_state.stage >= 3: st.write(f':{color}[Thank you!]') st.button('Start Over', on_click=set_state, args=[0]) Buttons to modify st.session_state If you modify st.session_state inside of a button, you must consider where that button is within the script. A slight problem In this example, we access st.session_state.name both before and after the buttons which modify it. When a button (" Jane " or " John ") is clicked, the script reruns. The info displayed before the buttons lags behind the info written after the button. The data in st.session_state before the button is not updated. When the script executes the button function, that is when the conditional code to update st.session_state creates the change. Thus, this change is reflected after the button. import streamlit as st import pandas as pd if 'name' not in st.session_state: st.session_state['name'] = 'John Doe' st.header(st.session_state['name']) if st.button('Jane'): st.session_state['name'] = 'Jane Doe' if st.button('John'): st.session_state['name'] = 'John Doe' st.header(st.session_state['name']) Logic used in a callback Callbacks are a clean way to modify st.session_state . Callbacks are executed as a prefix to the script rerunning, so the position of the button relative to accessing data is not important. import streamlit as st import pandas as pd if 'name' not in st.session_state: st.session_state['name'] = 'John Doe' def change_name(name): st.session_state['name'] = name st.header(st.session_state['name']) st.button('Jane', on_click=change_name, args=['Jane Doe']) st.button('John', on_click=change_name, args=['John Doe']) st.header(st.session_state['name']) Logic nested in a button with a rerun Although callbacks are often preferred to avoid extra reruns, our first 'John Doe'/'Jane Doe' example can be modified by adding st.rerun instead. If you need to acces data in st.session_state before the button that modifies it, you can include st.rerun to rerun the script after the change has been committed. This means the script will rerun twice when a button is clicked. import streamlit as st import pandas as pd if 'name' not in st.session_state: st.session_state['name'] = 'John Doe' st.header(st.session_state['name']) if st.button('Jane'): st.session_state['name'] = 'Jane Doe' st.rerun() if st.button('John'): st.session_state['name'] = 'John Doe' st.rerun() st.header(st.session_state['name']) Buttons to modify or reset other widgets When a button is used to modify or reset another widget, it is the same as the above examples to modify st.session_state . However, an extra consideration exists: you cannot modify a key-value pair in st.session_state if the widget with that key has already been rendered on the page for the current script run. priority_high Important Don't do this! import streamlit as st st.text_input('Name', key='name') # These buttons will error because their nested code changes # a widget's state after that widget within the script. if st.button('Clear name'): st.session_state.name = '' if st.button('Streamlit!'): st.session_state.name = ('Streamlit') Option 1: Use a key for the button and put the logic before the widget If you assign a key to a button, you can condition code on a button's state by using its value in st.session_state . This means that logic depending on your button can be in your script before that button. In the following example, we use the .get() method on st.session_state because the keys for the buttons will not exist when the script runs for the first time. The .get() method will return False if it can't find the key. Otherwise, it will return the value of the key. import streamlit as st # Use the get method since the keys won't be in session_state # on the first script run if st.session_state.get('clear'): st.session_state['name'] = '' if st.session_state.get('streamlit'): st.session_state['name'] = 'Streamlit' st.text_input('Name', key='name') st.button('Clear name', key='clear') st.button('Streamlit!', key='streamlit') Option 2: Use a callback import streamlit as st st.text_input('Name', key='name') def set_name(name): st.session_state.name = name st.button('Clear name', on_click=set_name, args=['']) st.button('Streamlit!', on_click=set_name, args=['Streamlit']) Option 3: Use containers By using st.container you can have widgets appear in different orders in your script and frontend view (webpage). import streamlit as st begin = st.container() if st.button('Clear name'): st.session_state.name = '' if st.button('Streamlit!'): st.session_state.name = ('Streamlit') # The widget is second in logic, but first in display begin.text_input('Name', key='name') Buttons to add other widgets dynamically When dynamically adding widgets to the page, make sure to use an index to keep the keys unique and avoid a DuplicateWidgetID error. In this example, we define a function display_input_row which renders a row of widgets. That function accepts an index as a parameter. The widgets rendered by display_input_row use index within their keys so that display_input_row can be executed multiple times on a single script rerun without repeating any widget keys. import streamlit as st def display_input_row(index): left, middle, right = st.columns(3) left.text_input('First', key=f'first_{index}') middle.text_input('Middle', key=f'middle_{index}') right.text_input('Last', key=f'last_{index}') if 'rows' not in st.session_state: st.session_state['rows'] = 0 def increase_rows(): st.session_state['rows'] += 1 st.button('Add person', on_click=increase_rows) for i in range(st.session_state['rows']): display_input_row(i) # Show the results st.subheader('People') for i in range(st.session_state['rows']): st.write( f'Person {i+1}:', st.session_state[f'first_{i}'], st.session_state[f'middle_{i}'], st.session_state[f'last_{i}'] ) Buttons to handle expensive or file-writing processes When you have expensive processes, set them to run upon clicking a button and save the results into st.session_state . This allows you to keep accessing the results of the process without re-executing it unnecessarily. This is especially helpful for processes that save to disk or write to a database. In this example, we have an expensive_process that depends on two parameters: option and add . Functionally, add changes the output, but option does not— option is there to provide a parameter import streamlit as st import pandas as pd import time def expensive_process(option, add): with st.spinner('Processing...'): time.sleep(5) df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C':[7, 8, 9]}) + add return (df, add) cols = st.columns(2) option = cols[0].selectbox('Select a number', options=['1', '2', '3']) add = cols[1].number_input('Add a number', min_value=0, max_value=10) if 'processed' not in st.session_state: st.session_state.processed = {} # Process and save results if st.button('Process'): result = expensive_process(option, add) st.session_state.processed[option] = result st.write(f'Option {option} processed with add {add}') result[0] Astute observers may think, "This feels a little like caching." We are only saving results relative to one parameter, but the pattern could easily be expanded to save results relative to both parameters. In that sense, yes, it has some similarities to caching, but also some important differences. When you save results in st.session_state , the results are only available to the current user in their current session. If you use st.cache_data instead, the results are available to all users across all sessions. Furthermore, if you want to update a saved result, you have to clear all saved results for that function to do so. Anti-patterns Here are some simplified examples of how buttons can go wrong. Be on the lookout for these common mistakes. Buttons nested inside buttons import streamlit as st if st.button('Button 1'): st.write('Button 1 was clicked') if st.button('Button 2'): # This will never be executed. st.write('Button 2 was clicked') Other widgets nested inside buttons import streamlit as st if st.button('Sign up'): name = st.text_input('Name') if name: # This will never be executed. st.success(f'Welcome {name}') Nesting a process inside a button without saving to session state import streamlit as st import pandas as pd file = st.file_uploader("Upload a file", type="csv") if st.button('Get data'): df = pd.read_csv(file) # This display will go away with the user's next action. st.write(df) if st.button('Save'): # This will always error. df.to_csv('data.csv') Previous: Animate & update elements Next: Dataframes forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.column_config.NumberColumn_-_Streamlit_Docs.txt | st.column_config.NumberColumn - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements remove st.dataframe st.data_editor st.column_config remove Column Text column Number column Checkbox column Selectbox column Datetime column Date column Time column List column Link column Image column Area chart column Line chart column Bar chart column Progress column st.table st.metric st.json Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Data elements / st.column_config / Number column st.column_config.NumberColumn Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure a number column in st.dataframe or st.data_editor . This is the default column type for integer and float values. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor . When used with st.data_editor , editing will be enabled with a numeric input widget. Function signature [source] st.column_config.NumberColumn(label=None, *, width=None, help=None, disabled=None, required=None, pinned=None, default=None, format=None, min_value=None, max_value=None, step=None) Parameters label (str or None) The label shown at the top of the column. If this is None (default), the column name is used. width ("small", "medium", "large", or None) The display width of the column. If this is None (default), the column will be sized to fit the cell contents. Otherwise, this can be one of the following: "small" : 75px wide "medium" : 200px wide "large" : 400px wide help (str or None) An optional tooltip that gets displayed when hovering over the column label. If this is None (default), no tooltip is displayed. disabled (bool or None) Whether editing should be disabled for this column. If this is None (default), Streamlit will decide: indices are disabled and data columns are not. If a column has mixed types, it may become uneditable regardless of disabled . required (bool or None) Whether edited cells in the column need to have a value. If this is False (default), the user can submit empty values for this column. If this is True , an edited cell in this column can only be submitted if its value is not None , and a new row will only be submitted after the user fills in this column. pinned (bool or None) Whether the column is pinned. A pinned column will stay visible on the left side no matter where the user scrolls. If this is None (default), Streamlit will decide: index columns are pinned, and data columns are not pinned. default (int, float, or None) Specifies the default value in this column when a new row is added by the user. This defaults to None . format (str or None) A printf-style format string controlling how numbers are displayed. This does not impact the return value. The following formatters are valid: %d , %e , %f , %g , %i , %u . You can also add prefixes and suffixes, e.g. "$ %.2f" to show a dollar prefix. If this is None (default), the numbers are not formatted. Number formatting from column_config always takes precedence over number formatting from pandas.Styler . min_value (int, float, or None) The minimum value that can be entered. If this is None (default), there will be no minimum. max_value (int, float, or None) The maximum value that can be entered. If this is None (default), there will be no maximum. step (int, float, or None) The precision of numbers that can be entered. If this None (default), integer columns will have a step of 1 and float columns will have unrestricted precision. In this case, some floats may display like integers. Setting step for float columns will ensure a consistent number of digits after the decimal even without setting format . Examples import pandas as pd import streamlit as st data_df = pd.DataFrame( { "price": [20, 950, 250, 500], } ) st.data_editor( data_df, column_config={ "price": st.column_config.NumberColumn( "Price (in USD)", help="The price of the product in USD", min_value=0, max_value=1000, step=1, format="$%d", ) }, hide_index=True, ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: Text column Next: Checkbox column forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
How_to_install_a_package_not_on_PyPI_Conda_but_ava.txt | How to install a package not on PyPI/Conda but available on GitHub - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Knowledge base / Installing dependencies / How to install a package not on PyPI or Conda but available on GitHub How to install a package not on PyPI/Conda but available on GitHub Overview Are you trying to deploy your app to Streamlit Community Cloud , but don't know how to specify a Python dependency in your requirements file that is available on a public GitHub repo but not any package index like PyPI or Conda? If so, continue reading to find out how! Let's suppose you want to install SomePackage and its Python dependencies from GitHub, a hosting service for the popular version control system (VCS) Git. And suppose SomePackage is found at the the following URL: https://github.com/SomePackage.git . pip (via requirements.txt ) supports installing from GitHub. This support requires a working executable to be available (for Git). It is used through a URL prefix: git+ . Specify the GitHub web URL To install SomePackage , innclude the following in your requirements.txt file: git+https://github.com/SomePackage#egg=SomePackage You can even specify a "git ref" such as branch name, a commit hash or a tag name, as shown in the examples below. Specify a Git branch name Install SomePackage by specifying a branch name such as main , master , develop , etc, in requirements.txt : git+https://github.com/SomePackage.git@main#egg=SomePackage Specify a commit hash Install SomePackage by specifying a commit hash in requirements.txt : git+https://github.com/SomePackage.git@eb40b4ff6f7c5c1e4366cgfg0671291bge918#egg=SomePackage Specify a tag Install SomePackage by specifying a tag in requirements.txt : git+https://github.com/[email protected]#egg=SomePackage Limitations It is currently not possible to install private packages from private GitHub repos using the URI form: git+https://{token}@github.com/user/project.git@{version} where version is a tag, a branch, or a commit. And token is a personal access token with read only permissions. Streamlit Community Cloud only supports installing public packages from public GitHub repos. Previous: Installing dependencies Next: ImportError libGL.so.1 cannot open shared object file No such file or directory forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.feedback_-_Streamlit_Docs.txt | st.feedback - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets remove BUTTONS st.button st.download_button st.form_submit_button link st.link_button st.page_link SELECTIONS st.checkbox st.color_picker st.feedback st.multiselect st.pills st.radio st.segmented_control st.selectbox st.select_slider st.toggle NUMERIC st.number_input st.slider DATE & TIME st.date_input st.time_input TEXT st.chat_input link st.text_area st.text_input MEDIA & FILES st.audio_input st.camera_input st.data_editor link st.file_uploader Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Input widgets / st.feedback st.feedback Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a feedback widget. A feedback widget is an icon-based button group available in three styles, as described in options . It is commonly used in chat and AI apps to allow users to rate responses. Function signature [source] st.feedback(options="thumbs", *, key=None, disabled=False, on_change=None, args=None, kwargs=None) Parameters options ("thumbs", "faces", or "stars") The feedback options displayed to the user. options can be one of the following: "thumbs" (default): Streamlit displays a thumb-up and thumb-down button group. "faces" : Streamlit displays a row of five buttons with facial expressions depicting increasing satisfaction from left to right. "stars" : Streamlit displays a row of star icons, allowing the user to select a rating from one to five stars. key (str or int) An optional string or integer to use as the unique key for the widget. If this is omitted, a key will be generated for the widget based on its content. No two widgets may have the same key. disabled (bool) An optional boolean that disables the feedback widget if set to True . The default is False . on_change (callable) An optional callback invoked when this feedback widget's value changes. args (tuple) An optional tuple of args to pass to the callback. kwargs (dict) An optional dict of kwargs to pass to the callback. Returns (int or None) An integer indicating the user's selection, where 0 is the lowest feedback. Higher values indicate more positive feedback. If no option was selected, the widget returns None . For options="thumbs" , a return value of 0 indicates thumbs-down, and 1 indicates thumbs-up. For options="faces" and options="stars" , return values range from 0 (least satisfied) to 4 (most satisfied). Examples Display a feedback widget with stars, and show the selected sentiment: import streamlit as st sentiment_mapping = ["one", "two", "three", "four", "five"] selected = st.feedback("stars") if selected is not None: st.markdown(f"You selected {sentiment_mapping[selected]} star(s).") Built with Streamlit 🎈 Fullscreen open_in_new Display a feedback widget with thumbs, and show the selected sentiment: import streamlit as st sentiment_mapping = [":material/thumb_down:", ":material/thumb_up:"] selected = st.feedback("thumbs") if selected is not None: st.markdown(f"You selected: {sentiment_mapping[selected]}") Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.color_picker Next: st.multiselect forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Start_and_stop_a_streaming_fragment___Streamlit_Do.txt | Start and stop a streaming fragment - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow remove FRAGMENTS Rerun your app from a fragment Create a multiple-container fragment Start and stop a streaming fragment Connect to data sources add Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Execution flow / Start and stop a streaming fragment Start and stop a streaming fragment Streamlit lets you turn functions into fragments , which can rerun independently from the full script. Additionally, you can tell Streamlit to rerun a fragment at a set time interval. This is great for streaming data or monitoring processes. You may want the user to start and stop this live streaming. To do this, programmatically set the run_every parameter for your fragment. Applied concepts Use a fragment to stream live data. Start and stop a fragment from automatically rerunning. Prerequisites The following must be installed in your Python environment: streamlit>=1.37.0 You should have a clean working directory called your-repository . You should have a basic understanding of fragments. Summary In this example, you'll build an app that streams two data series in a line chart. Your app will gather recent data on the first load of a session and statically display the line chart. Two buttons in the sidebar will allow users to start and stop data streaming to update the chart in real time. You'll use a fragment to manage the frequency and scope of the live updates. Here's a look at what you'll build: Complete code expand_more import streamlit as st import pandas as pd import numpy as np from datetime import datetime, timedelta def get_recent_data(last_timestamp): """Generate and return data from last timestamp to now, at most 60 seconds.""" now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) data = pd.DataFrame(sample_values, index=timestamps, columns=["A", "B"]) return data if "data" not in st.session_state: st.session_state.data = get_recent_data(datetime.now() - timedelta(seconds=60)) if "stream" not in st.session_state: st.session_state.stream = False def toggle_streaming(): st.session_state.stream = not st.session_state.stream st.title("Data feed") st.sidebar.slider( "Check for updates every: (seconds)", 0.5, 5.0, value=1.0, key="run_every" ) st.sidebar.button( "Start streaming", disabled=st.session_state.stream, on_click=toggle_streaming ) st.sidebar.button( "Stop streaming", disabled=not st.session_state.stream, on_click=toggle_streaming ) if st.session_state.stream is True: run_every = st.session_state.run_every else: run_every = None @st.fragment(run_every=run_every) def show_latest_data(): last_timestamp = st.session_state.data.index[-1] st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] st.line_chart(st.session_state.data) show_latest_data() Built with Streamlit 🎈 Fullscreen open_in_new Build the example Initialize your app In your_repository , create a file named app.py . In a terminal, change directories to your_repository and start your app. streamlit run app.py Your app will be blank since you still need to add code. In app.py , write the following: import streamlit as st import pandas as pd import numpy as np from datetime import datetime, timedelta You'll be using these libraries as follows: You'll work with two data series in a pandas.DataFrame . You'll generate random data with numpy . The data will have datetime.datetime index values. Save your app.py file and view your running app. Click " Always rerun " or hit your " A " key in your running app. Your running preview will automatically update as you save changes to app.py . Your preview will still be blank. Return to your code. Build a function to generate random, recent data To begin with, you'll define a function to randomly generate some data for two time series, which you'll call "A" and "B." It's okay to skip this section if you just want to copy the function. Complete function to randomly generate sales data expand_more def get_recent_data(last_timestamp): """Generate and return data from last timestamp to now, at most 60 seconds.""" now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) data = pd.DataFrame(sample_values, index=timestamps, columns=["A", "B"]) return data Start your function definition. def get_recent_data(last_timestamp): """Generate and return data from last timestamp to now, at most 60 seconds.""" You'll pass the timestamp of your most recent datapoint to your data-generating function. Your function will use this to only return new data. Get the current time and adjust the last timestamp if it is over 60 seconds ago. now = datetime.now() if now - last_timestamp > timedelta(seconds=60): last_timestamp = now - timedelta(seconds=60) By updating the last timestamp, you'll ensure the function never returns more than 60 seconds of data. Declare a new variable, sample_time , to define the time between datapoints. Calculate the timestamp of the first, new datapoint. sample_time = timedelta(seconds=0.5) # time between data points next_timestamp = last_timestamp + sample_time Create a datetime.datetime index and generate two data series of the same length. timestamps = np.arange(next_timestamp, now, sample_time) sample_values = np.random.randn(len(timestamps), 2) Combine the data series with the index into a pandas.DataFrame and return the data. data = pd.DataFrame(sample_values, index=timestamps, columns=["A", "B"]) return data Optional: Test out your function by calling it and displaying the data. data = get_recent_data(datetime.now() - timedelta(seconds=60)) data Save your app.py file to see the preview. Delete these two lines when finished. Initialize Session State values for your app Since you will dynamically change the run_every parameter of @st.fragment() , you'll need to initialize the associated variables and Session State values before defining your fragment function. Your fragment function will also read and update values in Session State, so you can define those now to make the fragment function easier to understand. Initialize your data for the first app load in a session. if "data" not in st.session_state: st.session_state.data = get_recent_data(datetime.now() - timedelta(seconds=60)) Your app will display this initial data in a static line chart before a user starts streaming data. Initialize "stream" in Session State to turn streaming on and off. Set the default to off ( False ). if "stream" not in st.session_state: st.session_state.stream = False Create a callback function to toggle "stream" between True and False . def toggle_streaming(): st.session_state.stream = not st.session_state.stream Add a title to your app. st.title("Data feed") Add a slider to the sidebar to set how frequently to check for data while streaming. st.sidebar.slider( "Check for updates every: (seconds)", 0.5, 5.0, value=1.0, key="run_every" ) Add buttons to the sidebar to turn streaming on and off. st.sidebar.button( "Start streaming", disabled=st.session_state.stream, on_click=toggle_streaming ) st.sidebar.button( "Stop streaming", disabled=not st.session_state.stream, on_click=toggle_streaming ) Both functions use the same callback to toggle "stream" in Session State. Use the current value "stream" to disable one of the buttons. This ensures the buttons are always consistent with the current state; " Start streaming " is only clickable when streaming is off, and " Stop streaming " is only clickable when streaming is on. The buttons also provide status to the user by highlighting which action is available to them. Create and set a new variable, run_every , that will determine whether or not the fragment function will rerun automatically (and how fast). if st.session_state.stream is True: run_every = st.session_state.run_every else: run_every = None Build a fragment function to stream data To allow the user to turn data streaming on and off, you must set the run_every parameter in the @st.fragment() decorator. Complete function to show and stream data expand_more @st.fragment(run_every=run_every) def show_latest_data(): last_timestamp = st.session_state.data.index[-1] st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] st.line_chart(st.session_state.data) Use an @st.fragment decorator and start your function definition. @st.fragment(run_every=run_every) def show_latest_data(): Use the run_every variable declared above to set the parameter of the same name. Retrieve the timestamp of the last datapoint in Session State. last_timestamp = st.session_state.data.index[-1] Update the data in Session State and trim to keep only the last 100 timestamps. st.session_state.data = pd.concat( [st.session_state.data, get_recent_data(last_timestamp)] ) st.session_state.data = st.session_state.data[-100:] Show the data in a line chart. st.line_chart(st.session_state.data) Your fragment-function definition is complete. Call and test out your fragment function Call your function at the bottom of your code. show_latest_data() Test out your app by clicking " Start streaming ." Try adjusting the frequency of updates. Next steps Try adjusting the frequency of data generation or how much data is kept in Session State. Within get_recent_data try setting sample_time with a widget. Try using st.plotly_chart or st.altair_chart to add labels to your chart. Previous: Create a multiple-container fragment Next: Connect to data sources forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Install_Streamlit_using_command_line___Streamlit_D.txt | Install Streamlit using command line - Streamlit Docs Documentation search Search rocket_launch Get started Installation remove Use command line Use Anaconda Distribution Use GitHub Codespaces Use Snowflake Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Get started / Installation / Use command line Install Streamlit using command line This page will walk you through creating an environment with venv and installing Streamlit with pip . These are our recommended tools, but if you are familiar with others you can use your favorite ones too. At the end, you'll build a simple "Hello world" app and run it. If you prefer to have a graphical interface to manage your Python environments, check out how to Install Streamlit using Anaconda Distribution . Prerequisites As with any programming tool, in order to install Streamlit you first need to make sure your computer is properly set up. More specifically, you’ll need: Python We support version 3.9 to 3.13 . A Python environment manager (recommended) Environment managers create virtual environments to isolate Python package installations between projects. We recommend using virtual environments because installing or upgrading a Python package may cause unintentional effects on another package. For a detailed introduction to Python environments, check out Python Virtual Environments: A Primer . For this guide, we'll be using venv , which comes with Python. A Python package manager Package managers handle installing each of your Python packages, including Streamlit. For this guide, we'll be using pip , which comes with Python. Only on MacOS: Xcode command line tools Download Xcode command line tools using these instructions in order to let the package manager install some of Streamlit's dependencies. A code editor Our favorite editor is VS Code , which is also what we use in all our tutorials. Create an environment using venv Open a terminal and navigate to your project folder. cd myproject In your terminal, type: python -m venv .venv A folder named ".venv" will appear in your project. This directory is where your virtual environment and its dependencies are installed. Activate your environment In your terminal, activate your environment with one of the following commands, depending on your operating system. # Windows command prompt .venv\Scripts\activate.bat # Windows PowerShell .venv\Scripts\Activate.ps1 # macOS and Linux source .venv/bin/activate Once activated, you will see your environment name in parentheses before your prompt. "(.venv)" Install Streamlit in your environment In the terminal with your environment activated, type: pip install streamlit Test that the installation worked by launching the Streamlit Hello example app: streamlit hello If this doesn't work, use the long-form command: python -m streamlit hello Streamlit's Hello app should appear in a new tab in your web browser! Built with Streamlit 🎈 Fullscreen open_in_new Close your terminal when you are done. Create a "Hello World" app and run it Create a file named app.py in your project folder. import streamlit as st st.write("Hello world") Any time you want to use your new environment, you first need to go to your project folder (where the .venv directory lives) and run the command to activate it: # Windows command prompt .venv\Scripts\activate.bat # Windows PowerShell .venv\Scripts\Activate.ps1 # macOS and Linux source .venv/bin/activate Once activated, you will see your environment's name in parentheses at the beginning of your terminal prompt. "(.venv)" Run your Streamlit app. streamlit run app.py If this doesn't work, use the long-form command: python -m streamlit run app.py To stop the Streamlit server, press Ctrl+C in the terminal. When you're done using this environment, return to your normal shell by typing: deactivate What's next? Read about our Basic concepts to understand Streamlit's dataflow model. Previous: Installation Next: Use Anaconda Distribution forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Work_with_Streamlit_elements_-_Streamlit_Docs.txt | Work with Streamlit elements - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements remove CHARTS Annotate an Altair chart DATAFRAMES Get dataframe row-selections Execution flow add Connect to data sources add Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Elements Previous: Tutorials Next: Annotate an Altair chart forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.vega_lite_chart_-_Streamlit_Docs.txt | st.vega_lite_chart - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements remove SIMPLE st.area_chart st.bar_chart st.line_chart st.map st.scatter_chart ADVANCED st.altair_chart st.bokeh_chart st.graphviz_chart st.plotly_chart st.pydeck_chart st.pyplot st.vega_lite_chart Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Chart elements / st.vega_lite_chart st.vega_lite_chart Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a chart using the Vega-Lite library. Vega-Lite is a high-level grammar for defining interactive graphics. Function signature [source] st.vega_lite_chart(data=None, spec=None, *, use_container_width=False, theme="streamlit", key=None, on_select="ignore", selection_mode=None, **kwargs) Parameters data (Anything supported by st.dataframe) Either the data to be plotted or a Vega-Lite spec containing the data (which more closely follows the Vega-Lite API). spec (dict or None) The Vega-Lite spec for the chart. If spec is None (default), Streamlit uses the spec passed in data . You cannot pass a spec to both data and spec . See https://vega.github.io/vega-lite/docs/ for more info. use_container_width (bool) Whether to override the figure's native width with the width of the parent container. If use_container_width is False (default), Streamlit sets the width of the chart to fit its contents according to the plotting library, up to the width of the parent container. If use_container_width is True , Streamlit sets the width of the figure to match the width of the parent container. theme ("streamlit" or None) The theme of the chart. If theme is "streamlit" (default), Streamlit uses its own design default. If theme is None , Streamlit falls back to the default behavior of the library. key (str) An optional string to use for giving this element a stable identity. If key is None (default), this element's identity will be determined based on the values of the other parameters. Additionally, if selections are activated and key is provided, Streamlit will register the key in Session State to store the selection state. The selection state is read-only. on_select ("ignore", "rerun", or callable) How the figure should respond to user selection events. This controls whether or not the figure behaves like an input widget. on_select can be one of the following: "ignore" (default): Streamlit will not react to any selection events in the chart. The figure will not behave like an input widget. "rerun" : Streamlit will rerun the app when the user selects data in the chart. In this case, st.vega_lite_chart will return the selection data as a dictionary. A callable : Streamlit will rerun the app and execute the callable as a callback function before the rest of the app. In this case, st.vega_lite_chart will return the selection data as a dictionary. To use selection events, the Vega-Lite spec defined in data or spec must include selection parameters from the the charting library. To learn about defining interactions in Vega-Lite, see Dynamic Behaviors with Parameters in Vega-Lite's documentation. selection_mode (str or Iterable of str) The selection parameters Streamlit should use. If selection_mode is None (default), Streamlit will use all selection parameters defined in the chart's Vega-Lite spec. When Streamlit uses a selection parameter, selections from that parameter will trigger a rerun and be included in the selection state. When Streamlit does not use a selection parameter, selections from that parameter will not trigger a rerun and not be included in the selection state. Selection parameters are identified by their name property. **kwargs (any) The Vega-Lite spec for the chart as keywords. This is an alternative to spec . Returns (element or dict) If on_select is "ignore" (default), this command returns an internal placeholder for the chart element that can be used with the .add_rows() method. Otherwise, this command returns a dictionary-like object that supports both key and attribute notation. The attributes are described by the VegaLiteState dictionary schema. Example import streamlit as st import pandas as pd import numpy as np chart_data = pd.DataFrame(np.random.randn(200, 3), columns=["a", "b", "c"]) st.vega_lite_chart( chart_data, { "mark": {"type": "circle", "tooltip": True}, "encoding": { "x": {"field": "a", "type": "quantitative"}, "y": {"field": "b", "type": "quantitative"}, "size": {"field": "c", "type": "quantitative"}, "color": {"field": "c", "type": "quantitative"}, }, }, ) Built with Streamlit 🎈 Fullscreen open_in_new Examples of Vega-Lite usage without Streamlit can be found at https://vega.github.io/vega-lite/examples/ . Most of those can be easily translated to the syntax shown above. Chart selections VegaLiteState Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake The schema for the Vega-Lite event state. The event state is stored in a dictionary-like object that supports both key and attribute notation. Event states cannot be programmatically changed or set through Session State. Only selection events are supported at this time. Attributes selection (dict) The state of the on_select event. This attribute returns a dictionary-like object that supports both key and attribute notation. The name of each Vega-Lite selection parameter becomes an attribute in the selection dictionary. The format of the data within each attribute is determined by the selection parameter definition within Vega-Lite. Examples The following two examples have equivalent definitions. Each one has a point and interval selection parameter include in the chart definition. The point selection parameter is named "point_selection" . The interval or box selection parameter is named "interval_selection" . The follow example uses st.altair_chart : import streamlit as st import pandas as pd import numpy as np import altair as alt if "data" not in st.session_state: st.session_state.data = pd.DataFrame( np.random.randn(20, 3), columns=["a", "b", "c"] ) df = st.session_state.data point_selector = alt.selection_point("point_selection") interval_selector = alt.selection_interval("interval_selection") chart = ( alt.Chart(df) .mark_circle() .encode( x="a", y="b", size="c", color="c", tooltip=["a", "b", "c"], fillOpacity=alt.condition(point_selector, alt.value(1), alt.value(0.3)), ) .add_params(point_selector, interval_selector) ) event = st.altair_chart(chart, key="alt_chart", on_select="rerun") event The following example uses st.vega_lite_chart : import streamlit as st import pandas as pd import numpy as np if "data" not in st.session_state: st.session_state.data = pd.DataFrame( np.random.randn(20, 3), columns=["a", "b", "c"] ) spec = { "mark": {"type": "circle", "tooltip": True}, "params": [ {"name": "interval_selection", "select": "interval"}, {"name": "point_selection", "select": "point"}, ], "encoding": { "x": {"field": "a", "type": "quantitative"}, "y": {"field": "b", "type": "quantitative"}, "size": {"field": "c", "type": "quantitative"}, "color": {"field": "c", "type": "quantitative"}, "fillOpacity": { "condition": {"param": "point_selection", "value": 1}, "value": 0.3, }, }, } event = st.vega_lite_chart( st.session_state.data, spec, key="vega_chart", on_select="rerun" ) event Try selecting points in this interactive example. When you click a point, the selection will appear under the attribute, "point_selection" , which is the name given to the point selection parameter. Similarly, when you make an interval selection, it will appear under the attribute "interval_selection" . You can give your selection parameters other names if desired. If you hold Shift while selecting points, existing point selections will be preserved. Interval selections are not preserved when making additional selections. Built with Streamlit 🎈 Fullscreen open_in_new element.add_rows Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Concatenate a dataframe to the bottom of the current one. Function signature [source] element.add_rows(data=None, **kwargs) Parameters data (pandas.DataFrame, pandas.Styler, pyarrow.Table, numpy.ndarray, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame, Iterable, dict, or None) Table to concat. Optional. **kwargs (pandas.DataFrame, numpy.ndarray, Iterable, dict, or None) The named dataset to concat. Optional. You can only pass in 1 dataset (including the one in the data parameter). Example import streamlit as st import pandas as pd import numpy as np df1 = pd.DataFrame( np.random.randn(50, 20), columns=("col %d" % i for i in range(20)) ) my_table = st.table(df1) df2 = pd.DataFrame( np.random.randn(50, 20), columns=("col %d" % i for i in range(20)) ) my_table.add_rows(df2) # Now the table shown in the Streamlit app contains the data for # df1 followed by the data for df2. You can do the same thing with plots. For example, if you want to add more data to a line chart: # Assuming df1 and df2 from the example above still exist... my_chart = st.line_chart(df1) my_chart.add_rows(df2) # Now the chart shown in the Streamlit app contains the data for # df1 followed by the data for df2. And for plots whose datasets are named, you can pass the data with a keyword argument where the key is the name: my_chart = st.vega_lite_chart( { "mark": "line", "encoding": {"x": "a", "y": "b"}, "datasets": { "some_fancy_name": df1, # <-- named dataset }, "data": {"name": "some_fancy_name"}, } ) my_chart.add_rows(some_fancy_name=df2) # <-- name used as keyword Theming Vega-Lite charts are displayed using the Streamlit theme by default. This theme is sleek, user-friendly, and incorporates Streamlit's color palette. The added benefit is that your charts better integrate with the rest of your app's design. The Streamlit theme is available from Streamlit 1.16.0 through the theme="streamlit" keyword argument. To disable it, and use Vega-Lite's native theme, use theme=None instead. Let's look at an example of charts with the Streamlit theme and the native Vega-Lite theme: import streamlit as st from vega_datasets import data source = data.cars() chart = { "mark": "point", "encoding": { "x": { "field": "Horsepower", "type": "quantitative", }, "y": { "field": "Miles_per_Gallon", "type": "quantitative", }, "color": {"field": "Origin", "type": "nominal"}, "shape": {"field": "Origin", "type": "nominal"}, }, } tab1, tab2 = st.tabs(["Streamlit theme (default)", "Vega-Lite native theme"]) with tab1: # Use the Streamlit theme. # This is the default. So you can also omit the theme argument. st.vega_lite_chart( source, chart, theme="streamlit", use_container_width=True ) with tab2: st.vega_lite_chart( source, chart, theme=None, use_container_width=True ) Click the tabs in the interactive app below to see the charts with the Streamlit theme enabled and disabled. Built with Streamlit 🎈 Fullscreen open_in_new If you're wondering if your own customizations will still be taken into account, don't worry! You can still make changes to your chart configurations. In other words, although we now enable the Streamlit theme by default, you can overwrite it with custom colors or fonts. For example, if you want a chart line to be green instead of the default red, you can do it! Previous: st.pyplot Next: Input widgets forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Media_elements_-_Streamlit_Docs.txt | Media elements - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements remove st.audio st.image st.logo st.video Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Media elements Media elements It's easy to embed images, videos, and audio files directly into your Streamlit apps. Image Display an image or list of images. st.image(numpy_array) st.image(image_bytes) st.image(file) st.image("https://example.com/myimage.jpg") Logo Display a logo in the upper-left corner of your app and its sidebar. st.logo("logo.jpg") Audio Display an audio player. st.audio(numpy_array) st.audio(audio_bytes) st.audio(file) st.audio("https://example.com/myaudio.mp3", format="audio/mp3") Video Display a video player. st.video(numpy_array) st.video(video_bytes) st.video(file) st.video("https://example.com/myvideo.mp4", format="video/mp4") Third-party components These are featured components created by our lovely community. For more examples and inspiration, check out our Components Gallery and Streamlit Extras ! Previous Streamlit Cropper A simple image cropper for Streamlit. Created by @turner-anderson . from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image Coordinates Get the coordinates of clicks on an image. Created by @blackary . from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit Lottie Integrate Lottie animations inside your Streamlit app. Created by @andfanilo . lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit Webrtc Handling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx . from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable Canvas Provides a sketching canvas using Fabric.js . Created by @andfanilo . from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image Comparison Compare images with a slider using JuxtaposeJS . Created by @fcakyon . from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit Cropper A simple image cropper for Streamlit. Created by @turner-anderson . from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image Coordinates Get the coordinates of clicks on an image. Created by @blackary . from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit Lottie Integrate Lottie animations inside your Streamlit app. Created by @andfanilo . lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Streamlit Webrtc Handling and transmitting real-time video/audio streams with Streamlit. Created by @whitphx . from streamlit_webrtc import webrtc_streamer webrtc_streamer(key="sample") Drawable Canvas Provides a sketching canvas using Fabric.js . Created by @andfanilo . from streamlit_drawable_canvas import st_canvas st_canvas(fill_color="rgba(255, 165, 0, 0.3)", stroke_width=stroke_width, stroke_color=stroke_color, background_color=bg_color, background_image=Image.open(bg_image) if bg_image else None, update_streamlit=realtime_update, height=150, drawing_mode=drawing_mode, point_display_radius=point_display_radius if drawing_mode == 'point' else 0, key="canvas",) Image Comparison Compare images with a slider using JuxtaposeJS . Created by @fcakyon . from streamlit_image_comparison import image_comparison image_comparison(img1="image1.jpg", img2="image2.jpg",) Streamlit Cropper A simple image cropper for Streamlit. Created by @turner-anderson . from streamlit_cropper import st_cropper st_cropper(img, realtime_update=realtime_update, box_color=box_color, aspect_ratio=aspect_ratio) Image Coordinates Get the coordinates of clicks on an image. Created by @blackary . from streamlit_image_coordinates import streamlit_image_coordinates streamlit_image_coordinates("https://placekitten.com/200/300") Streamlit Lottie Integrate Lottie animations inside your Streamlit app. Created by @andfanilo . lottie_hello = load_lottieurl("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") st_lottie(lottie_hello, key="hello") Next Previous: Input widgets Next: st.audio forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Quick_reference_-_Streamlit_Docs.txt | Quick reference - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference remove Cheat sheet Release notes add Pre-release features Roadmap open_in_new web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Quick reference Quick reference Cheatsheet A dense list of Streamlit commands with example syntax. Release notes See how Streamlit has changed with each new version. Pre-release features Understand how we introduce new features and how you can get your hands on them sooner! Roadmap Get a sneak peek at what we have scheduled for the next year. Previous: Tutorials Next: Cheat sheet forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Quickstart_-_Streamlit_Docs.txt | Quickstart - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started remove Quickstart Create your account Connect your GitHub account Explore your workspace Deploy from a template Fork and edit a public app Trust and security Deploy your app add Manage your app add Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Get started / Quickstart Quickstart This is a concise set of steps to create your Streamlit Community Cloud account, deploy a sample app, and start editing it with GitHub Codespaces. For other options and complete explanations, start with Create your account . You will sign in to your GitHub account during this process. Community Cloud will use the email from your GitHub account to create your Community Cloud account. For other sign-in options, see Create your account . Prerequisites You must have a GitHub account. Sign up for Streamlit Community Cloud Go to share.streamlit.io . Click " Continue to sign-in ." Click " Continue with GitHub ." Enter your GitHub credentials and follow GitHub's authentication prompts. Fill in your account information, and click " I accept " at the bottom. Add access to your public repositories In the upper-left corner, click " Workspaces warning ." From the drop down, click " Connect GitHub account ." Enter your GitHub credentials and follow GitHub's authentication prompts. Click " Authorize streamlit ." Optional: Add access to private repositories In the upper-left corner, click on your GitHub username. From the drop down, click " Settings ." On the left side of the dialog, select " Linked accounts ." Under "Source control," click " Connect here arrow_forward ." Click " Authorize streamlit ." Create a new app from a template In the upper-right corner, click " Create app ." When asked "Do you already have an app?" click " Nope, create one from a template ." From the list of templates on the left, select " Blank app ." At the bottom, select the option to " Open GitHub Codespaces... " At the bottom, click " Deploy ." Edit your app in GitHub Codespaces Wait for GitHub to set up your codespace. It can take several minutes to fully initialize your codespace. After the Visual Studio Code editor appears in your codespace, it can take several minutes to install Python and start the Streamlit server. When complete, a split screen view displays a code editor on the left and a running app on the right. The code editor opens two tabs by default: the repository's readme file and the app's entrypoint file. Go to the app's entrypoint file ( streamlit_app.py ) in the left pane, and change line 3 by adding "Streamlit" inside st.title . -st.title("🎈 My new app") +st.title("🎈 My new Streamlit app") Files are automatically saved in your codespace with each edit. A moment after typing a change, your app on the right side will display a rerun prompt. Click " Always rerun ." If the rerun prompt disappears before you click it, you can hover over the overflow menu icon ( more_vert ) to bring it back. Optional: Continue to make edits and observe the changes within seconds. Publish your changes In the left navigation bar, click the source control icon. In the source control sidebar on the left, enter a name for your commit. Click " check Commit ." To stage and commit all your changes, in the confirmation dialog, click " Yes ." Your changes are committed locally in your codespace. To push your commit to GitHub, in the source control sidebar on the left, click " cached 1 arrow_upward ." To push commits to "origin/main," in the confirmation dialog, click " OK ." Your changes are now saved to your GitHub repository. Community Cloud will immediately reflect the changes in your deployed app. Optional: To see your updated, published app, return to the " My apps " section of your workspace at share.streamlit.io , and click on your app. Stop or delete your codespace When you stop interacting with your codespace, GitHub will generally stop your codespace for you. However, the surest way to avoid undesired use of your capacity is to stop or delete your codespace when you are done. Go to github.com/codespaces . At the bottom of the page, all your codespaces are listed. Click the overflow menu icon ( more_horiz ) for your codespace. If you want to return to your work later, click " Stop codespace ." Otherwise, click " Delete ." Congratulations! You just deployed an app to Streamlit Community Cloud. 🎉 Return to your workspace at share.streamlit.io/ and deploy another Streamlit app . Previous: Get started Next: Create your account forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
secrets.toml_-_Streamlit_Docs.txt | secrets.toml - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets remove SECRETS st.secrets secrets.toml CONNECTIONS st.connection SnowflakeConnection SQLConnection BaseConnection SnowparkConnection delete Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Connections and secrets / secrets.toml secrets.toml secrets.toml is an optional file you can define for your working directory or global development environment. When secrets.toml is defined both globally and in your working directory, Streamlit combines the secrets and gives precendence to the working-directory secrets. For more information, see Secrets management . File location To define your secrets locally or per-project, add .streamlit/secrets.toml to your working directory. Your working directory is wherever you call streamlit run . If you haven't previously created the .streamlit directory, you will need to add it. To define your configuration globally, you must first locate your global .streamlit directory. Streamlit adds this hidden directory to your OS user profile during installation. For MacOS/Linux, this will be ~/.streamlit/secrets.toml . For Windows, this will be %userprofile%/.streamlit/secrets.toml . Optionally, you can change where Streamlit searches for secrets through the configuration option, secrets.files . File format secrets.toml is a TOML file. Example OpenAI_key = "your OpenAI key" whitelist = ["sally", "bob", "joe"] [database] user = "your username" password = "your password" In your Streamlit app, the following values would be true: st.secrets["OpenAI_key"] == "your OpenAI key" "sally" in st.secrets.whitelist st.secrets["database"]["user"] == "your username" st.secrets.database.password == "your password" Previous: st.secrets Next: st.connection forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.fragment_-_Streamlit_Docs.txt | st.fragment - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow remove st.dialog st.form st.form_submit_button st.fragment st.rerun st.stop Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Execution flow / st.fragment st.fragment Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Decorator to turn a function into a fragment which can rerun independently of the full app. When a user interacts with an input widget created inside a fragment, Streamlit only reruns the fragment instead of the full app. If run_every is set, Streamlit will also rerun the fragment at the specified interval while the session is active, even if the user is not interacting with your app. To trigger an app rerun from inside a fragment, call st.rerun() directly. To trigger a fragment rerun from within itself, call st.rerun(scope="fragment") . Any values from the fragment that need to be accessed from the wider app should generally be stored in Session State. When Streamlit element commands are called directly in a fragment, the elements are cleared and redrawn on each fragment rerun, just like all elements are redrawn on each app rerun. The rest of the app is persisted during a fragment rerun. When a fragment renders elements into externally created containers, the elements will not be cleared with each fragment rerun. Instead, elements will accumulate in those containers with each fragment rerun, until the next app rerun. Calling st.sidebar in a fragment is not supported. To write elements to the sidebar with a fragment, call your fragment function inside a with st.sidebar context manager. Fragment code can interact with Session State, imported modules, and other Streamlit elements created outside the fragment. Note that these interactions are additive across multiple fragment reruns. You are responsible for handling any side effects of that behavior. Warning Fragments can only contain widgets in their main body. Fragments can't render widgets to externally created containers. Function signature [source] st.fragment(func=None, *, run_every=None) Parameters func (callable) The function to turn into a fragment. run_every (int, float, timedelta, str, or None) The time interval between automatic fragment reruns. This can be one of the following: None (default). An int or float specifying the interval in seconds. A string specifying the time in a format supported by Pandas' Timedelta constructor , e.g. "1d" , "1.5 days" , or "1h23s" . A timedelta object from Python's built-in datetime library , e.g. timedelta(days=1) . If run_every is None , the fragment will only rerun from user-triggered events. Examples The following example demonstrates basic usage of @st.fragment . As an analogy, "inflating balloons" is a slow process that happens outside of the fragment. "Releasing balloons" is a quick process that happens inside of the fragment. import streamlit as st import time @st.fragment def release_the_balloons(): st.button("Release the balloons", help="Fragment rerun") st.balloons() with st.spinner("Inflating balloons..."): time.sleep(5) release_the_balloons() st.button("Inflate more balloons", help="Full rerun") Built with Streamlit 🎈 Fullscreen open_in_new This next example demonstrates how elements both inside and outside of a fragement update with each app or fragment rerun. In this app, clicking "Rerun full app" will increment both counters and update all values displayed in the app. In contrast, clicking "Rerun fragment" will only increment the counter within the fragment. In this case, the st.write command inside the fragment will update the app's frontend, but the two st.write commands outside the fragment will not update the frontend. import streamlit as st if "app_runs" not in st.session_state: st.session_state.app_runs = 0 st.session_state.fragment_runs = 0 @st.fragment def my_fragment(): st.session_state.fragment_runs += 1 st.button("Rerun fragment") st.write(f"Fragment says it ran {st.session_state.fragment_runs} times.") st.session_state.app_runs += 1 my_fragment() st.button("Rerun full app") st.write(f"Full app says it ran {st.session_state.app_runs} times.") st.write(f"Full app sees that fragment ran {st.session_state.fragment_runs} times.") Built with Streamlit 🎈 Fullscreen open_in_new You can also trigger an app rerun from inside a fragment by calling st.rerun . import streamlit as st if "clicks" not in st.session_state: st.session_state.clicks = 0 @st.fragment def count_to_five(): if st.button("Plus one!"): st.session_state.clicks += 1 if st.session_state.clicks % 5 == 0: st.rerun() return count_to_five() st.header(f"Multiples of five clicks: {st.session_state.clicks // 5}") if st.button("Check click count"): st.toast(f"## Total clicks: {st.session_state.clicks}") Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.form_submit_button Next: st.rerun forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.column_config.TextColumn_-_Streamlit_Docs.txt | st.column_config.TextColumn - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements remove st.dataframe st.data_editor st.column_config remove Column Text column Number column Checkbox column Selectbox column Datetime column Date column Time column List column Link column Image column Area chart column Line chart column Bar chart column Progress column st.table st.metric st.json Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Data elements / st.column_config / Text column st.column_config.TextColumn Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure a text column in st.dataframe or st.data_editor . This is the default column type for string values. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor . When used with st.data_editor , editing will be enabled with a text input widget. Function signature [source] st.column_config.TextColumn(label=None, *, width=None, help=None, disabled=None, required=None, pinned=None, default=None, max_chars=None, validate=None) Parameters label (str or None) The label shown at the top of the column. If this is None (default), the column name is used. width ("small", "medium", "large", or None) The display width of the column. If this is None (default), the column will be sized to fit the cell contents. Otherwise, this can be one of the following: "small" : 75px wide "medium" : 200px wide "large" : 400px wide help (str or None) An optional tooltip that gets displayed when hovering over the column label. If this is None (default), no tooltip is displayed. disabled (bool or None) Whether editing should be disabled for this column. If this is None (default), Streamlit will decide: indices are disabled and data columns are not. If a column has mixed types, it may become uneditable regardless of disabled . required (bool or None) Whether edited cells in the column need to have a value. If this is False (default), the user can submit empty values for this column. If this is True , an edited cell in this column can only be submitted if its value is not None , and a new row will only be submitted after the user fills in this column. pinned (bool or None) Whether the column is pinned. A pinned column will stay visible on the left side no matter where the user scrolls. If this is None (default), Streamlit will decide: index columns are pinned, and data columns are not pinned. default (str or None) Specifies the default value in this column when a new row is added by the user. This defaults to None . max_chars (int or None) The maximum number of characters that can be entered. If this is None (default), there will be no maximum. validate (str or None) A JS-flavored regular expression (e.g. "^[a-z]+$" ) that edited values are validated against. If the user input is invalid, it will not be submitted. Examples import pandas as pd import streamlit as st data_df = pd.DataFrame( { "widgets": ["st.selectbox", "st.number_input", "st.text_area", "st.button"], } ) st.data_editor( data_df, column_config={ "widgets": st.column_config.TextColumn( "Widgets", help="Streamlit **widget** commands 🎈", default="st.", max_chars=50, validate=r"^st\.[a-z_]+$", ) }, hide_index=True, ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: Column Next: Number column forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Favorite_your_app_-_Streamlit_Docs.txt | Favorite your app - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app add Manage your app remove App analytics App settings Delete your app Edit your app Favorite your app Reboot your app Rename your app in GitHub Upgrade Python Upgrade Streamlit Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Manage your app / Favorite your app Favorite your app Streamlit Community Cloud supports a "favorite" feature that lets you quickly access your apps from your workspace. Favorited apps appear at the top of their workspace with a yellow star ( star ) beside them. You can favorite and unfavorite apps in any workspace to which you have access as a developer or invited viewer. push_pin Note Favorites are specific to your account. Other members of your workspace cannot see which apps you have favorited. Favoriting and unfavoriting your app You can favorite your app: From your workspace . From your app ! Favorite your app from your workspace From your workspace at share.streamlit.io , hover over your app. If your app is not yet favorited, a star outline ( star_border ) will appear on hover. Click on the star ( star_border / star ) next to your app name to toggle its favorited status. Favorite your app from your app toolbar From your app at <your-custom-subdomain>.streamlit.app , click the star ( star_border / star ) in the upper-right corner to toggle your app's favorited status. Previous: Edit your app Next: Reboot your app forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.secrets_-_Streamlit_Docs.txt | st.secrets - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets remove SECRETS st.secrets secrets.toml CONNECTIONS st.connection SnowflakeConnection SQLConnection BaseConnection SnowparkConnection delete Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Connections and secrets / st.secrets st.secrets st.secrets provides a dictionary-like interface to access secrets stored in a secrets.toml file. It behaves similarly to st.session_state . st.secrets can be used with both key and attribute notation. For example, st.secrets.your_key and st.secrets["your_key"] refer to the same value. For more information about using st.secrets , see Secrets management . secrets.toml By default, secrets can be saved globally or per-project. When both types of secrets are saved, Streamlit will combine the saved values but give precedence to per-project secrets if there are duplicate keys. For information on how to format and locate your secrets.toml file for your development environment, see secrets.toml . Configure secrets locations You can configure where Streamlit searches for secrets through the configuration option, secrets.files . With this option, you can list additional secrets locations and change the order of precedence. You can specify other TOML files or include Kubernetes style secret files. Example OpenAI_key = "your OpenAI key" whitelist = ["sally", "bob", "joe"] [database] user = "your username" password = "your password" In your Streamlit app, the following values would be true: st.secrets["OpenAI_key"] == "your OpenAI key" "sally" in st.secrets.whitelist st.secrets["database"]["user"] == "your username" st.secrets.database.password == "your password" Previous: Connections and secrets Next: secrets.toml forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.error_-_Streamlit_Docs.txt | st.error - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements remove CALLOUTS st.success st.info st.warning st.error st.exception OTHER st.progress st.spinner st.status st.toast st.balloons st.snow Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Status elements / st.error st.error Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display error message. Function signature [source] st.error(body, *, icon=None) Parameters body (str) The error text to display. icon (str, None) An optional emoji or icon to display next to the alert. If icon is None (default), no icon is displayed. If icon is a string, the following options are valid: A single-character emoji. For example, you can set icon="🚨" or icon="🔥" . Emoji short codes are not supported. An icon from the Material Symbols library (rounded style) in the format ":material/icon_name:" where "icon_name" is the name of the icon in snake case. For example, icon=":material/thumb_up:" will display the Thumb Up icon. Find additional icons in the Material Symbols font library. Example import streamlit as st st.error('This is an error', icon="🚨") Previous: st.warning Next: st.exception forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Streamlit_documentation.txt | Streamlit documentation Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Streamlit documentation Streamlit is an open-source Python framework for data scientists and AI/ML engineers to deliver dynamic data apps with only a few lines of code. Build and deploy powerful data apps in minutes. Let's get started! install_desktop Setup and installation Get set up to start working with Streamlit. dvr API reference Learn about our APIs, with actionable explanations of specific functions and features. grid_view App gallery Try out awesome apps created by our users, and curated from our forums or Twitter. How to use our docs rocket_launch Get started with Streamlit! Set up your development environment and learn the fundamental concepts, and start coding! description Develop your Streamlit app! Our API reference explains each Streamlit function with examples. Dive deep into all of our features with conceptual guides. Try out our step-by-step tutorials. cloud Deploy your Streamlit app! Streamlit Community Cloud our free platform for deploying and sharing Streamlit apps. Streamlit in Snowflake is an enterprise-class solution where you can house your data and apps in one, unified, global system. Explore all your options! school Knowledge base is a self-serve library of tips, tricks, and articles that answer your questions about creating and deploying Streamlit apps. What's new view_column Add borders to columns and metrics st.columns and st.metric have a new border parameter to show an optional border. palette Primary color in Markdown Now you can use the color "primary" in Markdown to color or highlight text with your app's primary color. push_pin Pin or freeze dataframe columns Column configuration has a new pinned parameter to pin columns on the left as users scroll horizontally. ads_click Tertiary buttons Buttons have a new, "tertiary" type for a more subtle appearance. more_horiz Pills You can create a single- or multi-select group of pill-buttons. view_week Segmented control You can create a segmented button or button group. Latest blog posts View all updates Join the community Streamlit is more than just a way to make data apps, it's also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions, ideas, and help you work through your bugs — stop by today! View forum Other Media GitHub View the Streamlit source code and issue tracker. YouTube Watch screencasts made by the Streamlit team and the community. Twitter Follow @streamlit on Twitter to keep up with the latest news. LinkedIn Follow @streamlit on the world's largest professional network. Newsletter Sign up for communications from Streamlit. Next: Get started Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.column_config.DateColumn_-_Streamlit_Docs.txt | st.column_config.DateColumn - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements remove st.dataframe st.data_editor st.column_config remove Column Text column Number column Checkbox column Selectbox column Datetime column Date column Time column List column Link column Image column Area chart column Line chart column Bar chart column Progress column st.table st.metric st.json Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Data elements / st.column_config / Date column st.column_config.DateColumn Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure a date column in st.dataframe or st.data_editor . This is the default column type for date values. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor . When used with st.data_editor , editing will be enabled with a date picker widget. Function signature [source] st.column_config.DateColumn(label=None, *, width=None, help=None, disabled=None, required=None, pinned=None, default=None, format=None, min_value=None, max_value=None, step=None) Parameters label (str or None) The label shown at the top of the column. If this is None (default), the column name is used. width ("small", "medium", "large", or None) The display width of the column. If this is None (default), the column will be sized to fit the cell contents. Otherwise, this can be one of the following: "small" : 75px wide "medium" : 200px wide "large" : 400px wide help (str or None) An optional tooltip that gets displayed when hovering over the column label. If this is None (default), no tooltip is displayed. disabled (bool or None) Whether editing should be disabled for this column. If this is None (default), Streamlit will decide: indices are disabled and data columns are not. If a column has mixed types, it may become uneditable regardless of disabled . required (bool or None) Whether edited cells in the column need to have a value. If this is False (default), the user can submit empty values for this column. If this is True , an edited cell in this column can only be submitted if its value is not None , and a new row will only be submitted after the user fills in this column. pinned (bool or None) Whether the column is pinned. A pinned column will stay visible on the left side no matter where the user scrolls. If this is None (default), Streamlit will decide: index columns are pinned, and data columns are not pinned. default (datetime.date or None) Specifies the default value in this column when a new row is added by the user. This defaults to None . format (str or None) A momentJS format string controlling how times are displayed. See momentJS docs for available formats. If this is None (default), the format is YYYY-MM-DD . Number formatting from column_config always takes precedence over number formatting from pandas.Styler . min_value (datetime.date or None) The minimum date that can be entered. If this is None (default), there will be no minimum. max_value (datetime.date or None) The maximum date that can be entered. If this is None (default), there will be no maximum. step (int or None) The stepping interval in days. If this is None (default), the step will be 1 day. Examples from datetime import date import pandas as pd import streamlit as st data_df = pd.DataFrame( { "birthday": [ date(1980, 1, 1), date(1990, 5, 3), date(1974, 5, 19), date(2001, 8, 17), ] } ) st.data_editor( data_df, column_config={ "birthday": st.column_config.DateColumn( "Birthday", min_value=date(1900, 1, 1), max_value=date(2005, 1, 1), format="DD.MM.YYYY", step=1, ), }, hide_index=True, ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: Datetime column Next: Time column forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Widget_updating_for_every_second_input_when_using_.txt | Widget updating for every second input when using session state - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Knowledge base / FAQ / Widget updating for every second input when using session state Widget updating for every second input when using session state Overview You are using session state to store page interactions in your app. When users interact with a widget in your app (e.g., click a button), you expect your app to update its widget states and reflect the new values. However, you notice that it doesn't. Instead, users have to interact with the widget twice (e.g., click a button twice) for the app to show the correct values. What do you do now? 🤔 Let's walk through the solution in the section below. Solution When using session state to update widgets or values in your script, you need to use the unique key you assigned to the widget, not the variable that you assigned your widget to. In the example code block below, the unique key assigned to the slider widget is slider , and the variable the widget is assigned to is slide_val . Let's see this in an example. Say you want a user to click a button that resets a slider. To have the slider's value update on the button click, you need to use a callback function with the on_click parameter of st.button : # the callback function for the button will add 1 to the # slider value up to 10 def plus_one(): if st.session_state["slider"] < 10: st.session_state.slider += 1 else: pass return # when creating the button, assign the name of your callback # function to the on_click parameter add_one = st.button("Add one to the slider", on_click=plus_one, key="add_one") # create the slider slide_val = st.slider("Pick a number", 0, 10, key="slider") Relevant resources Caching Sqlite DB connection resulting in glitchy rendering of the page Select all checkbox that is linked to selectbox of options Previous: Where does st.file_uploader store uploaded files and when do they get deleted? Next: Why does Streamlit restrict nested st.columns? forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.column_config.LinkColumn_-_Streamlit_Docs.txt | st.column_config.LinkColumn - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements remove st.dataframe st.data_editor st.column_config remove Column Text column Number column Checkbox column Selectbox column Datetime column Date column Time column List column Link column Image column Area chart column Line chart column Bar chart column Progress column st.table st.metric st.json Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Data elements / st.column_config / Link column st.column_config.LinkColumn Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure a link column in st.dataframe or st.data_editor . The cell values need to be string and will be shown as clickable links. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor . When used with st.data_editor , editing will be enabled with a text input widget. Function signature [source] st.column_config.LinkColumn(label=None, *, width=None, help=None, disabled=None, required=None, pinned=None, default=None, max_chars=None, validate=None, display_text=None) Parameters label (str or None) The label shown at the top of the column. If this is None (default), the column name is used. width ("small", "medium", "large", or None) The display width of the column. If this is None (default), the column will be sized to fit the cell contents. Otherwise, this can be one of the following: "small" : 75px wide "medium" : 200px wide "large" : 400px wide help (str or None) An optional tooltip that gets displayed when hovering over the column label. If this is None (default), no tooltip is displayed. disabled (bool or None) Whether editing should be disabled for this column. If this is None (default), Streamlit will decide: indices are disabled and data columns are not. If a column has mixed types, it may become uneditable regardless of disabled . required (bool or None) Whether edited cells in the column need to have a value. If this is False (default), the user can submit empty values for this column. If this is True , an edited cell in this column can only be submitted if its value is not None , and a new row will only be submitted after the user fills in this column. pinned (bool or None) Whether the column is pinned. A pinned column will stay visible on the left side no matter where the user scrolls. If this is None (default), Streamlit will decide: index columns are pinned, and data columns are not pinned. default (str or None) Specifies the default value in this column when a new row is added by the user. This defaults to None . max_chars (int or None) The maximum number of characters that can be entered. If this is None (default), there will be no maximum. validate (str or None) A JS-flavored regular expression (e.g. "^https://.+$" ) that edited values are validated against. If the user input is invalid, it will not be submitted. display_text (str or None) The text that is displayed in the cell. This can be one of the following: None (default) to display the URL itself. A string that is displayed in every cell, e.g. "Open link" . A JS-flavored regular expression (detected by usage of parentheses) to extract a part of the URL via a capture group. For example, use "https://(.*?)\.example\.com" to extract the display text "foo" from the URL "https://foo.example.com". For more complex cases, you may use Pandas Styler's format function on the underlying dataframe. Note that this makes the app slow, doesn't work with editable columns, and might be removed in the future. Text formatting from column_config always takes precedence over text formatting from pandas.Styler . Examples import pandas as pd import streamlit as st data_df = pd.DataFrame( { "apps": [ "https://roadmap.streamlit.app", "https://extras.streamlit.app", "https://issues.streamlit.app", "https://30days.streamlit.app", ], "creator": [ "https://github.com/streamlit", "https://github.com/arnaudmiribel", "https://github.com/streamlit", "https://github.com/streamlit", ], } ) st.data_editor( data_df, column_config={ "apps": st.column_config.LinkColumn( "Trending apps", help="The top trending Streamlit apps", validate=r"^https://[a-z]+\.streamlit\.app$", max_chars=100, display_text=r"https://(.*?)\.streamlit\.app" ), "creator": st.column_config.LinkColumn( "App Creator", display_text="Open profile" ), }, hide_index=True, ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: List column Next: Image column forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.pyplot_-_Streamlit_Docs.txt | st.pyplot - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements remove SIMPLE st.area_chart st.bar_chart st.line_chart st.map st.scatter_chart ADVANCED st.altair_chart st.bokeh_chart st.graphviz_chart st.plotly_chart st.pydeck_chart st.pyplot st.vega_lite_chart Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Chart elements / st.pyplot st.pyplot Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Display a matplotlib.pyplot figure. Important You must install matplotlib to use this command. Function signature [source] st.pyplot(fig=None, clear_figure=None, use_container_width=True, **kwargs) Parameters fig (Matplotlib Figure) The Matplotlib Figure object to render. See https://matplotlib.org/stable/gallery/index.html for examples. Note When this argument isn't specified, this function will render the global Matplotlib figure object. However, this feature is deprecated and will be removed in a later version. clear_figure (bool) If True, the figure will be cleared after being rendered. If False, the figure will not be cleared after being rendered. If left unspecified, we pick a default based on the value of fig . If fig is set, defaults to False . If fig is not set, defaults to True . This simulates Jupyter's approach to matplotlib rendering. use_container_width (bool) Whether to override the figure's native width with the width of the parent container. If use_container_width is True (default), Streamlit sets the width of the figure to match the width of the parent container. If use_container_width is False , Streamlit sets the width of the chart to fit its contents according to the plotting library, up to the width of the parent container. **kwargs (any) Arguments to pass to Matplotlib's savefig function. Example import streamlit as st import matplotlib.pyplot as plt import numpy as np arr = np.random.normal(1, 1, size=100) fig, ax = plt.subplots() ax.hist(arr, bins=20) st.pyplot(fig) Built with Streamlit 🎈 Fullscreen open_in_new Matplotlib supports several types of "backends". If you're getting an error using Matplotlib with Streamlit, try setting your backend to "TkAgg": echo "backend: TkAgg" >> ~/.matplotlib/matplotlibrc For more information, see https://matplotlib.org/faq/usage_faq.html . priority_high Warning Matplotlib doesn't work well with threads . So if you're using Matplotlib you should wrap your code with locks as shown in the snippet below. This Matplotlib bug is more prominent when you deploy and share your app apps since you're more likely to get concurrent users then. from matplotlib.backends.backend_agg import RendererAgg _lock = RendererAgg.lock with _lock: fig.title('This is a figure)') fig.plot([1,20,3,40]) st.pyplot(fig) Previous: st.pydeck_chart Next: st.vega_lite_chart forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Create_an_app_-_Streamlit_Docs.txt | Create an app - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps remove Create an app Create a multipage app code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Get started / First steps / Create an app Create an app If you've made it this far, chances are you've installed Streamlit and run through the basics in Basic concepts and Advanced concepts . If not, now is a good time to take a look. The easiest way to learn how to use Streamlit is to try things out yourself. As you read through this guide, test each method. As long as your app is running, every time you add a new element to your script and save, Streamlit's UI will ask if you'd like to rerun the app and view the changes. This allows you to work in a fast interactive loop: you write some code, save it, review the output, write some more, and so on, until you're happy with the results. The goal is to use Streamlit to create an interactive app for your data or model and along the way to use Streamlit to review, debug, perfect, and share your code. In this guide, you're going to use Streamlit's core features to create an interactive app; exploring a public Uber dataset for pickups and drop-offs in New York City. When you're finished, you'll know how to fetch and cache data, draw charts, plot information on a map, and use interactive widgets, like a slider, to filter results. star Tip If you'd like to skip ahead and see everything at once, the complete script is available below . Create your first app Streamlit is more than just a way to make data apps, it’s also a community of creators that share their apps and ideas and help each other make their work better. Please come join us on the community forum. We love to hear your questions, ideas, and help you work through your bugs — stop by today! The first step is to create a new Python script. Let's call it uber_pickups.py . Open uber_pickups.py in your favorite IDE or text editor, then add these lines: import streamlit as st import pandas as pd import numpy as np Every good app has a title, so let's add one: st.title('Uber pickups in NYC') Now it's time to run Streamlit from the command line: streamlit run uber_pickups.py Running a Streamlit app is no different than any other Python script. Whenever you need to view the app, you can use this command. star Tip Did you know you can also pass a URL to streamlit run ? This is great when combined with GitHub Gists. For example: streamlit run https://raw.githubusercontent.com/streamlit/demo-uber-nyc-pickups/master/streamlit_app.py As usual, the app should automatically open in a new tab in your browser. Fetch some data Now that you have an app, the next thing you'll need to do is fetch the Uber dataset for pickups and drop-offs in New York City. Let's start by writing a function to load the data. Add this code to your script: DATE_COLUMN = 'date/time' DATA_URL = ('https://s3-us-west-2.amazonaws.com/' 'streamlit-demo-data/uber-raw-data-sep14.csv.gz') def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) lowercase = lambda x: str(x).lower() data.rename(lowercase, axis='columns', inplace=True) data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN]) return data You'll notice that load_data is a plain old function that downloads some data, puts it in a Pandas dataframe, and converts the date column from text to datetime. The function accepts a single parameter ( nrows ), which specifies the number of rows that you want to load into the dataframe. Now let's test the function and review the output. Below your function, add these lines: # Create a text element and let the reader know the data is loading. data_load_state = st.text('Loading data...') # Load 10,000 rows of data into the dataframe. data = load_data(10000) # Notify the reader that the data was successfully loaded. data_load_state.text('Loading data...done!') You'll see a few buttons in the upper-right corner of your app asking if you'd like to rerun the app. Choose Always rerun , and you'll see your changes automatically each time you save. Ok, that's underwhelming... It turns out that it takes a long time to download data, and load 10,000 lines into a dataframe. Converting the date column into datetime isn’t a quick job either. You don’t want to reload the data each time the app is updated – luckily Streamlit allows you to cache the data. Effortless caching Try adding @st.cache_data before the load_data declaration: @st.cache_data def load_data(nrows): Then save the script, and Streamlit will automatically rerun your app. Since this is the first time you’re running the script with @st.cache_data , you won't see anything change. Let’s tweak your file a little bit more so that you can see the power of caching. Replace the line data_load_state.text('Loading data...done!') with this: data_load_state.text("Done! (using st.cache_data)") Now save. See how the line you added appeared immediately? If you take a step back for a second, this is actually quite amazing. Something magical is happening behind the scenes, and it only takes one line of code to activate it. How's it work? Let's take a few minutes to discuss how @st.cache_data actually works. When you mark a function with Streamlit’s cache annotation, it tells Streamlit that whenever the function is called that it should check two things: The input parameters you used for the function call. The code inside the function. If this is the first time Streamlit has seen both these items, with these exact values, and in this exact combination, it runs the function and stores the result in a local cache. The next time the function is called, if the two values haven't changed, then Streamlit knows it can skip executing the function altogether. Instead, it reads the output from the local cache and passes it on to the caller -- like magic. "But, wait a second," you’re saying to yourself, "this sounds too good to be true. What are the limitations of all this awesomesauce?" Well, there are a few: Streamlit will only check for changes within the current working directory. If you upgrade a Python library, Streamlit's cache will only notice this if that library is installed inside your working directory. If your function is not deterministic (that is, its output depends on random numbers), or if it pulls data from an external time-varying source (for example, a live stock market ticker service) the cached value will be none-the-wiser. Lastly, you should avoid mutating the output of a function cached with st.cache_data since cached values are stored by reference. While these limitations are important to keep in mind, they tend not to be an issue a surprising amount of the time. Those times, this cache is really transformational. star Tip Whenever you have a long-running computation in your code, consider refactoring it so you can use @st.cache_data , if possible. Please read Caching for more details. Now that you know how caching with Streamlit works, let’s get back to the Uber pickup data. Inspect the raw data It's always a good idea to take a look at the raw data you're working with before you start working with it. Let's add a subheader and a printout of the raw data to the app: st.subheader('Raw data') st.write(data) In the Basic concepts guide you learned that st.write will render almost anything you pass to it. In this case, you're passing in a dataframe and it's rendering as an interactive table. st.write tries to do the right thing based on the data type of the input. If it isn't doing what you expect you can use a specialized command like st.dataframe instead. For a full list, see API reference . Draw a histogram Now that you've had a chance to take a look at the dataset and observe what's available, let's take things a step further and draw a histogram to see what Uber's busiest hours are in New York City. To start, let's add a subheader just below the raw data section: st.subheader('Number of pickups by hour') Use NumPy to generate a histogram that breaks down pickup times binned by hour: hist_values = np.histogram( data[DATE_COLUMN].dt.hour, bins=24, range=(0,24))[0] Now, let's use Streamlit's st.bar_chart() method to draw this histogram. st.bar_chart(hist_values) Save your script. This histogram should show up in your app right away. After a quick review, it looks like the busiest time is 17:00 (5 P.M.). To draw this diagram we used Streamlit's native bar_chart() method, but it's important to know that Streamlit supports more complex charting libraries like Altair, Bokeh, Plotly, Matplotlib and more. For a full list, see supported charting libraries . Plot data on a map Using a histogram with Uber's dataset helped us determine what the busiest times are for pickups, but what if we wanted to figure out where pickups were concentrated throughout the city. While you could use a bar chart to show this data, it wouldn't be easy to interpret unless you were intimately familiar with latitudinal and longitudinal coordinates in the city. To show pickup concentration, let's use Streamlit st.map() function to overlay the data on a map of New York City. Add a subheader for the section: st.subheader('Map of all pickups') Use the st.map() function to plot the data: st.map(data) Save your script. The map is fully interactive. Give it a try by panning or zooming in a bit. After drawing your histogram, you determined that the busiest hour for Uber pickups was 17:00. Let's redraw the map to show the concentration of pickups at 17:00. Locate the following code snippet: st.subheader('Map of all pickups') st.map(data) Replace it with: hour_to_filter = 17 filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter] st.subheader(f'Map of all pickups at {hour_to_filter}:00') st.map(filtered_data) You should see the data update instantly. To draw this map we used the st.map function that's built into Streamlit, but if you'd like to visualize complex map data, we encourage you to take a look at the st.pydeck_chart . Filter results with a slider In the last section, when you drew the map, the time used to filter results was hardcoded into the script, but what if we wanted to let a reader dynamically filter the data in real time? Using Streamlit's widgets you can. Let's add a slider to the app with the st.slider() method. Locate hour_to_filter and replace it with this code snippet: hour_to_filter = st.slider('hour', 0, 23, 17) # min: 0h, max: 23h, default: 17h Use the slider and watch the map update in real time. Use a button to toggle data Sliders are just one way to dynamically change the composition of your app. Let's use the st.checkbox function to add a checkbox to your app. We'll use this checkbox to show/hide the raw data table at the top of your app. Locate these lines: st.subheader('Raw data') st.write(data) Replace these lines with the following code: if st.checkbox('Show raw data'): st.subheader('Raw data') st.write(data) We're sure you've got your own ideas. When you're done with this tutorial, check out all the widgets that Streamlit exposes in our API Reference . Let's put it all together That's it, you've made it to the end. Here's the complete script for our interactive app. star Tip If you've skipped ahead, after you've created your script, the command to run Streamlit is streamlit run [app name] . import streamlit as st import pandas as pd import numpy as np st.title('Uber pickups in NYC') DATE_COLUMN = 'date/time' DATA_URL = ('https://s3-us-west-2.amazonaws.com/' 'streamlit-demo-data/uber-raw-data-sep14.csv.gz') @st.cache_data def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) lowercase = lambda x: str(x).lower() data.rename(lowercase, axis='columns', inplace=True) data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN]) return data data_load_state = st.text('Loading data...') data = load_data(10000) data_load_state.text("Done! (using st.cache_data)") if st.checkbox('Show raw data'): st.subheader('Raw data') st.write(data) st.subheader('Number of pickups by hour') hist_values = np.histogram(data[DATE_COLUMN].dt.hour, bins=24, range=(0,24))[0] st.bar_chart(hist_values) # Some number in the range 0-23 hour_to_filter = st.slider('hour', 0, 23, 17) filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter] st.subheader('Map of all pickups at %s:00' % hour_to_filter) st.map(filtered_data) Share your app After you’ve built a Streamlit app, it's time to share it! To show it off to the world you can use Streamlit Community Cloud to deploy, manage, and share your app for free. It works in 3 simple steps: Put your app in a public GitHub repo (and make sure it has a requirements.txt!) Sign into share.streamlit.io Click 'Deploy an app' and then paste in your GitHub URL That's it! 🎈 You now have a publicly deployed app that you can share with the world. Click to learn more about how to use Streamlit Community Cloud . Get help That's it for getting started, now you can go and build your own apps! If you run into difficulties here are a few things you can do. Check out our community forum and post a question Quick help from command line with streamlit help Go through our Knowledge Base for tips, step-by-step tutorials, and articles that answer your questions about creating and deploying Streamlit apps. Read more documentation! Check out: Concepts for things like caching, theming, and adding statefulness to apps. API reference for examples of every Streamlit command. Previous: First steps Next: Create a multipage app forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Navigation_and_pages_-_Streamlit_Docs.txt | Navigation and pages - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements add Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages remove st.navigation st.Page st.page_link link st.switch_page Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Navigation and pages Navigation and pages Navigation Configure the available pages in a multipage app. st.navigation({ "Your account" : [log_out, settings], "Reports" : [overview, usage], "Tools" : [search] }) Page Define a page in a multipage app. home = st.Page( "home.py", title="Home", icon=":material/home:" ) Page link Display a link to another page in a multipage app. st.page_link("app.py", label="Home", icon="🏠") st.page_link("pages/profile.py", label="Profile") Switch page Programmatically navigates to a specified page. st.switch_page("pages/my_page.py") Previous: Third-party components Next: st.navigation forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
st.column_config.Column_-_Streamlit_Docs.txt | st.column_config.Column - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference remove PAGE ELEMENTS Write and magic add Text elements add Data elements remove st.dataframe st.data_editor st.column_config remove Column Text column Number column Checkbox column Selectbox column Datetime column Date column Time column List column Link column Image column Area chart column Line chart column Bar chart column Progress column st.table st.metric st.json Chart elements add Input widgets add Media elements add Layouts and containers add Chat elements add Status elements add Third-party components open_in_new APPLICATION LOGIC Navigation and pages add Execution flow add Caching and state add Connections and secrets add Custom components add Utilities add Configuration add TOOLS App testing add Command line add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / API reference / Data elements / st.column_config / Column st.column_config.Column Streamlit Version Version 1.41.0 Version 1.40.0 Version 1.39.0 Version 1.38.0 Version 1.37.0 Version 1.36.0 Version 1.35.0 Version 1.34.0 Version 1.33.0 Version 1.32.0 Version 1.31.0 Version 1.30.0 Version 1.29.0 Version 1.28.0 Version 1.27.0 Version 1.26.0 Version 1.25.0 Version 1.24.0 Version 1.23.0 Version 1.22.0 Version 1.21.0 Version 1.20.0 Streamlit in Snowflake Configure a generic column in st.dataframe or st.data_editor . The type of the column will be automatically inferred from the data type. This command needs to be used in the column_config parameter of st.dataframe or st.data_editor . To change the type of the column and enable type-specific configuration options, use one of the column types in the st.column_config namespace, e.g. st.column_config.NumberColumn . Function signature [source] st.column_config.Column(label=None, *, width=None, help=None, disabled=None, required=None, pinned=None) Parameters label (str or None) The label shown at the top of the column. If this is None (default), the column name is used. width ("small", "medium", "large", or None) The display width of the column. If this is None (default), the column will be sized to fit the cell contents. Otherwise, this can be one of the following: "small" : 75px wide "medium" : 200px wide "large" : 400px wide help (str or None) An optional tooltip that gets displayed when hovering over the column label. If this is None (default), no tooltip is displayed. disabled (bool or None) Whether editing should be disabled for this column. If this is None (default), Streamlit will decide: indices are disabled and data columns are not. If a column has mixed types, it may become uneditable regardless of disabled . required (bool or None) Whether edited cells in the column need to have a value. If this is False (default), the user can submit empty values for this column. If this is True , an edited cell in this column can only be submitted if its value is not None , and a new row will only be submitted after the user fills in this column. pinned (bool or None) Whether the column is pinned. A pinned column will stay visible on the left side no matter where the user scrolls. If this is None (default), Streamlit will decide: index columns are pinned, and data columns are not pinned. Examples import pandas as pd import streamlit as st data_df = pd.DataFrame( { "widgets": ["st.selectbox", "st.number_input", "st.text_area", "st.button"], } ) st.data_editor( data_df, column_config={ "widgets": st.column_config.Column( "Streamlit Widgets", help="Streamlit **widget** commands 🎈", width="medium", required=True, ) }, hide_index=True, num_rows="dynamic", ) Built with Streamlit 🎈 Fullscreen open_in_new Previous: st.column_config Next: Text column forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Upgrade_your_app_s_Python_version_on_Community_Clo.txt | Upgrade your app's Python version on Community Cloud - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started add Deploy your app add Manage your app remove App analytics App settings Delete your app Edit your app Favorite your app Reboot your app Rename your app in GitHub Upgrade Python Upgrade Streamlit Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Manage your app / Upgrade Python Upgrade your app's Python version on Community Cloud Dependencies within Python can be upgraded in place by simply changing your environment configuration file (typically requirements.txt ). However, Python itself can't be changed after deployment. When you deploy an app, you can select the version of Python through the " Advanced settings " dialog. After you have deployed an app, you must delete it and redeploy it to change the version of Python it uses. Take note of your app's settings: Current, custom subdomain. GitHub coordinates (repository, branch, and entrypoint file path). Secrets. When you delete an app, its custom subdomain is immediately available for reuse. Delete your app . Deploy your app . On the deployment page, select your app's GitHub coordinates. Set your custom domain to match your deleted instance. Click " Advanced settings ." Choose your desired version of Python. Optional: If your app had secrets, re-enter them. Click " Save ." Click " Deploy ." In a few minutes, Community Cloud will redirect you to your redployed app. Previous: Rename your app in GitHub Next: Upgrade Streamlit forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Connect_Streamlit_to_Google_BigQuery___Streamlit_D.txt | Connect Streamlit to Google BigQuery - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials remove Elements add Execution flow add Connect to data sources remove AWS S3 BigQuery Firestore open_in_new Google Cloud Storage Microsoft SQL Server MongoDB MySQL Neon PostgreSQL Private Google Sheet Public Google Sheet Snowflake Supabase Tableau TiDB TigerGraph Multipage apps add Work with LLMs add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Tutorials / Connect to data sources / BigQuery Connect Streamlit to Google BigQuery Introduction This guide explains how to securely access a BigQuery database from Streamlit Community Cloud. It uses the google-cloud-bigquery library and Streamlit's Secrets management . Create a BigQuery database push_pin Note If you already have a database that you want to use, feel free to skip to the next step . For this example, we will use one of the sample datasets from BigQuery (namely the shakespeare table). If you want to create a new dataset instead, follow Google's quickstart guide . Enable the BigQuery API Programmatic access to BigQuery is controlled through Google Cloud Platform . Create an account or sign in and head over to the APIs & Services dashboard (select or create a project if asked). As shown below, search for the BigQuery API and enable it: Create a service account & key file To use the BigQuery API from Streamlit Community Cloud, you need a Google Cloud Platform service account (a special account type for programmatic data access). Go to the Service Accounts page and create an account with the Viewer permission (this will let the account access data but not change it): push_pin Note If the button CREATE SERVICE ACCOUNT is gray, you don't have the correct permissions. Ask the admin of your Google Cloud project for help. After clicking DONE , you should be back on the service accounts overview. Create a JSON key file for the new account and download it: Add the key file to your local app secrets Your local Streamlit app will read secrets from a file .streamlit/secrets.toml in your app's root directory. Create this file if it doesn't exist yet and add the content of the key file you just downloaded to it as shown below: # .streamlit/secrets.toml [gcp_service_account] type = "service_account" project_id = "xxx" private_key_id = "xxx" private_key = "xxx" client_email = "xxx" client_id = "xxx" auth_uri = "https://accounts.google.com/o/oauth2/auth" token_uri = "https://oauth2.googleapis.com/token" auth_provider_x509_cert_url = "https://www.googleapis.com/oauth2/v1/certs" client_x509_cert_url = "xxx" priority_high Important Add this file to .gitignore and don't commit it to your GitHub repo! Copy your app secrets to the cloud As the secrets.toml file above is not committed to GitHub, you need to pass its content to your deployed app (on Streamlit Community Cloud) separately. Go to the app dashboard and in the app's dropdown menu, click on Edit Secrets . Copy the content of secrets.toml into the text area. More information is available at Secrets management . Add google-cloud-bigquery to your requirements file Add the google-cloud-bigquery package to your requirements.txt file, preferably pinning its version (replace x.x.x with the version want installed): # requirements.txt google-cloud-bigquery==x.x.x Write your Streamlit app Copy the code below to your Streamlit app and run it. Make sure to adapt the query if you don't use the sample table. # streamlit_app.py import streamlit as st from google.oauth2 import service_account from google.cloud import bigquery # Create API client. credentials = service_account.Credentials.from_service_account_info( st.secrets["gcp_service_account"] ) client = bigquery.Client(credentials=credentials) # Perform query. # Uses st.cache_data to only rerun when the query changes or after 10 min. @st.cache_data(ttl=600) def run_query(query): query_job = client.query(query) rows_raw = query_job.result() # Convert to list of dicts. Required for st.cache_data to hash the return value. rows = [dict(row) for row in rows_raw] return rows rows = run_query("SELECT word FROM `bigquery-public-data.samples.shakespeare` LIMIT 10") # Print results. st.write("Some wise words from Shakespeare:") for row in rows: st.write("✍️ " + row['word']) See st.cache_data above? Without it, Streamlit would run the query every time the app reruns (e.g. on a widget interaction). With st.cache_data , it only runs when the query changes or after 10 minutes (that's what ttl is for). Watch out: If your database updates more frequently, you should adapt ttl or remove caching so viewers always see the latest data. Learn more in Caching . Alternatively, you can use pandas to read from BigQuery right into a dataframe! Follow all the above steps, install the pandas-gbq library (don't forget to add it to requirements.txt !), and call pandas.read_gbq(query, credentials=credentials) . More info in the pandas docs . If everything worked out (and you used the sample table), your app should look like this: Previous: AWS S3 Next: Firestore forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Get_started_with_Streamlit_Community_Cloud___Strea.txt | Get started with Streamlit Community Cloud - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud remove Get started remove Quickstart Create your account Connect your GitHub account Explore your workspace Deploy from a template Fork and edit a public app Trust and security Deploy your app add Manage your app add Share your app add Manage your account add Status and limitations Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Deploy / Streamlit Community Cloud / Get started Get started with Streamlit Community Cloud Welcome to Streamlit Community Cloud, where you can share your Streamlit apps with the world! Whether you've already created your first Streamlit app or you're just getting started, you're in the right place. First things first, you need to create your Streamlit Community Cloud account to start deploying apps. rocket_launch Quickstart Create your account and deploy an example app as fast as possible. Jump right into coding with GitHub Codespaces. security Trust and Security Security first! If you want to read up on how we handle your data before you get started, we've got you covered. If you're looking for help to build your first Streamlit app, read our Get started docs for the Streamlit library. If you want to fork an app and start with an example, check out our App gallery . Either way, it only takes a few minutes to create your first app. If you're looking for more detailed instructions than the quickstart, try the following: person Create your account. See all the options and get complete explanations as you create your Streamlit Community Cloud account. code Connect your GitHub account. After your create your Community Cloud account, connect GitHub for source control. computer Explore your workspace. Take a quick tour of your Community Cloud workspace. See where all the magic happens. auto_fix_high Deploy an app from a template. Use a template to get your own app up and running in minutes. fork_right Fork and edit a public app. Start with a bang! Fork a public app and jump right into the code. Previous: Streamlit Community Cloud Next: Quickstart forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
Widget_behavior_-_Streamlit_Docs.txt | Widget behavior - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts remove CORE Architecture & execution remove Running your app Streamlit's architecture The app chrome Caching Session State Forms Fragments Widget behavior Multipage apps add App design add ADDITIONAL Connections and secrets add Custom components add Configuration and theming add App testing add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Develop / Concepts / Architecture & execution / Widget behavior Understanding widget behavior Widgets (like st.button , st.selectbox , and st.text_input ) are at the heart of Streamlit apps. They are the interactive elements of Streamlit that pass information from your users into your Python code. Widgets are magical and often work how you want, but they can have surprising behavior in some situations. Understanding the different parts of a widget and the precise order in which events occur helps you achieve your desired results. This guide covers advanced concepts about widgets. Generally, it begins with simpler concepts and increases in complexity. For most beginning users, these details won't be important to know right away. When you want to dynamically change widgets or preserve widget information between pages, these concepts will be important to understand. We recommend having a basic understanding of Session State before reading this guide. 🎈 TL;DR expand_more The actions of one user do not affect the widgets of any other user. A widget function call returns the widget's current value, which is a simple Python type. (e.g. st.button returns a boolean value.) Widgets return their default values on their first call before a user interacts with them. A widget's identity depends on the arguments passed to the widget function. Changing a widget's label, min or max value, default value, placeholder text, help text, or key will cause it to reset. If you don't call a widget function in a script run, Streamlit will delete the widget's information— including its key-value pair in Session State . If you call the same widget function later, Streamlit treats it as a new widget. The last two points (widget identity and widget deletion) are the most relevant when dynamically changing widgets or working with multi-page applications. This is covered in detail later in this guide: Statefulness of widgets and Widget life cycle . Anatomy of a widget There are four parts to keep in mind when using widgets: The frontend component as seen by the user. The backend value or value as seen through st.session_state . The key of the widget used to access its value via st.session_state . The return value given by the widget's function. Widgets are session dependent Widget states are dependent on a particular session (browser connection). The actions of one user do not affect the widgets of any other user. Furthermore, if a user opens up multiple tabs to access an app, each tab will be a unique session. Changing a widget in one tab will not affect the same widget in another tab. Widgets return simple Python data types The value of a widget as seen through st.session_state and returned by the widget function are of simple Python types. For example, st.button returns a boolean value and will have the same boolean value saved in st.session_state if using a key. The first time a widget function is called (before a user interacts with it), it will return its default value. (e.g. st.selectbox returns the first option by default.) Default values are configurable for all widgets with a few special exceptions like st.button and st.file_uploader . Keys help distinguish widgets and access their values Widget keys serve two purposes: Distinguishing two otherwise identical widgets. Creating a means to access and manipulate the widget's value through st.session_state . Whenever possible, Streamlit updates widgets incrementally on the frontend instead of rebuilding them with each rerun. This means Streamlit assigns an ID to each widget from the arguments passed to the widget function. A widget's ID is based on parameters such as label, min or max value, default value, placeholder text, help text, and key. The page where the widget appears also factors into a widget's ID. If you have two widgets of the same type with the same arguments on the same page, you will get a DuplicateWidgetID error. In this case, assign unique keys to the two widgets. Streamlit can't understand two identical widgets on the same page # This will cause a DuplicateWidgetID error. st.button("OK") st.button("OK") Use keys to distinguish otherwise identical widgets st.button("OK", key="privacy") st.button("OK", key="terms") Order of operations When a user interacts with a widget, the order of logic is: Its value in st.session_state is updated. The callback function (if any) is executed. The page reruns with the widget function returning its new value. If the callback function writes anything to the screen, that content will appear above the rest of the page. A callback function runs as a prefix to the script rerunning. Consequently, that means anything written via a callback function will disappear as soon as the user performs their next action. Other widgets should generally not be created within a callback function. push_pin Note If a callback function is passed any args or kwargs, those arguments will be established when the widget is rendered. In particular, if you want to use a widget's new value in its own callback function, you cannot pass that value to the callback function via the args parameter; you will have to assign a key to the widget and look up its new value using a call to st.session_state within the callback function . Using callback functions with forms Using a callback function with a form requires consideration of this order of operations. import streamlit as st if "attendance" not in st.session_state: st.session_state.attendance = set() def take_attendance(): if st.session_state.name in st.session_state.attendance: st.info(f"{st.session_state.name} has already been counted.") else: st.session_state.attendance.add(st.session_state.name) with st.form(key="my_form"): st.text_input("Name", key="name") st.form_submit_button("I'm here!", on_click=take_attendance) Built with Streamlit 🎈 Fullscreen open_in_new Statefulness of widgets As long as the defining parameters of a widget remain the same and that widget is continuously rendered on the frontend, then it will be stateful and remember user input. Changing parameters of a widget will reset it If any of the defining parameters of a widget change, Streamlit will see it as a new widget and it will reset. The use of manually assigned keys and default values is particularly important in this case. Note that callback functions, callback args and kwargs, label visibility, and disabling a widget do not affect a widget's identity. In this example, we have a slider whose min and max values are changed. Try interacting with each slider to change its value then change the min or max setting to see what happens. import streamlit as st cols = st.columns([2, 1, 2]) minimum = cols[0].number_input("Minimum", 1, 5) maximum = cols[2].number_input("Maximum", 6, 10, 10) st.slider("No default, no key", minimum, maximum) st.slider("No default, with key", minimum, maximum, key="a") st.slider("With default, no key", minimum, maximum, value=5) st.slider("With default, with key", minimum, maximum, value=5, key="b") Built with Streamlit 🎈 Fullscreen open_in_new Updating a slider with no default value For the first two sliders above, as soon as the min or max value is changed, the sliders reset to the min value. The changing of the min or max value makes them "new" widgets from Streamlit's perspective and so they are recreated from scratch when the app reruns with the changed parameters. Since no default value is defined, each widget will reset to its min value. This is the same with or without a key since it's seen as a new widget either way. There is a subtle point to understand about pre-existing keys connecting to widgets. This will be explained further down in Widget life cycle . Updating a slider with a default value For the last two sliders above, a change to the min or max value will result in the widgets being seen as "new" and thus recreated like before. Since a default value of 5 is defined, each widget will reset to 5 whenever the min or max is changed. This is again the same (with or without a key). A solution to Retain statefulness when changing a widget's parameters is provided further on. Widgets do not persist when not continually rendered If a widget's function is not called during a script run, then none of its parts will be retained, including its value in st.session_state . If a widget has a key and you navigate away from that widget, its key and associated value in st.session_state will be deleted. Even temporarily hiding a widget will cause it to reset when it reappears; Streamlit will treat it like a new widget. You can either interrupt the Widget clean-up process (described at the end of this page) or save the value to another key. Save widget values in Session State to preserve them between pages If you want to navigate away from a widget and return to it while keeping its value, use a separate key in st.session_state to save the information independently from the widget. In this example, a temporary key is used with a widget. The temporary key uses an underscore prefix. Hence, "_my_key" is used as the widget key, but the data is copied to "my_key" to preserve it between pages. import streamlit as st def store_value(): # Copy the value to the permanent key st.session_state["my_key"] = st.session_state["_my_key"] # Copy the saved value to the temporary key st.session_state["_my_key"] = st.session_state["my_key"] st.number_input("Number of filters", key="_my_key", on_change=store_value) If this is functionalized to work with multiple widgets, it could look something like this: import streamlit as st def store_value(key): st.session_state[key] = st.session_state["_"+key] def load_value(key): st.session_state["_"+key] = st.session_state[key] load_value("my_key") st.number_input("Number of filters", key="_my_key", on_change=store_value, args=["my_key"]) Widget life cycle When a widget function is called, Streamlit will check if it already has a widget with the same parameters. Streamlit will reconnect if it thinks the widget already exists. Otherwise, it will make a new one. As mentioned earlier, Streamlit determines a widget's ID based on parameters such as label, min or max value, default value, placeholder text, help text, and key. The page name also factors into a widget's ID. On the other hand, callback functions, callback args and kwargs, label visibility, and disabling a widget do not affect a widget's identity. Calling a widget function when the widget doesn't already exist If your script rerun calls a widget function with changed parameters or calls a widget function that wasn't used on the last script run: Streamlit will build the frontend and backend parts of the widget, using its default value. If the widget has been assigned a key, Streamlit will check if that key already exists in Session State. a. If it exists and is not currently associated with another widget, Streamlit will assign that key's value to the widget. b. Otherwise, it will assign the default value to the key in st.session_state (creating a new key-value pair or overwriting an existing one). If there are args or kwargs for a callback function, they are computed and saved at this point in time. The widget value is then returned by the function. Step 2 can be tricky. If you have a widget: st.number_input("Alpha",key="A") and you change it on a page rerun to: st.number_input("Beta",key="A") Streamlit will see that as a new widget because of the label change. The key "A" will be considered part of the widget labeled "Alpha" and will not be attached as-is to the new widget labeled "Beta" . Streamlit will destroy st.session_state.A and recreate it with the default value. If a widget attaches to a pre-existing key when created and is also manually assigned a default value, you will get a warning if there is a disparity. If you want to control a widget's value through st.session_state , initialize the widget's value through st.session_state and avoid the default value argument to prevent conflict. Calling a widget function when the widget already exists When rerunning a script without changing a widget's parameters: Streamlit will connect to the existing frontend and backend parts. If the widget has a key that was deleted from st.session_state , then Streamlit will recreate the key using the current frontend value. (e.g Deleting a key will not revert the widget to a default value.) It will return the current value of the widget. Widget clean-up process When Streamlit gets to the end of a script run, it will delete the data for any widgets it has in memory that were not rendered on the screen. Most importantly, that means Streamlit will delete all key-value pairs in st.session_state associated with a widget not currently on screen. Additional examples As promised, let's address how to retain the statefulness of widgets when changing pages or modifying their parameters. There are two ways to do this. Use dummy keys to duplicate widget values in st.session_state and protect the data from being deleted along with the widget. Interrupt the widget clean-up process. The first method was shown above in Save widget values in Session State to preserve them between pages Interrupting the widget clean-up process To retain information for a widget with key="my_key" , just add this to the top of every page: st.session_state.my_key = st.session_state.my_key When you manually save data to a key in st.session_state , it will become detached from any widget as far as the clean-up process is concerned. If you navigate away from a widget with some key "my_key" and save data to st.session_state.my_key on the new page, you will interrupt the widget clean-up process and prevent the key-value pair from being deleted or overwritten if another widget with the same key exists. Retain statefulness when changing a widget's parameters Here is a solution to our earlier example of changing a slider's min and max values. This solution interrupts the clean-up process as described above. import streamlit as st # Set default value if "a" not in st.session_state: st.session_state.a = 5 cols = st.columns(2) minimum = cols[0].number_input("Min", 1, 5, key="min") maximum = cols[1].number_input("Max", 6, 10, 10, key="max") def update_value(): # Helper function to ensure consistency between widget parameters and value st.session_state.a = min(st.session_state.a, maximum) st.session_state.a = max(st.session_state.a, minimum) # Validate the slider value before rendering update_value() st.slider("A", minimum, maximum, key="a") Built with Streamlit 🎈 Fullscreen open_in_new The update_value() helper function is actually doing two things. On the surface, it's making sure there are no inconsistent changes to the parameters values as described. Importantly, it's also interrupting the widget clean-up process. When the min or max value of the widget changes, Streamlit sees it as a new widget on rerun. Without saving a value to st.session_state.a , the value would be thrown out and replaced by the "new" widget's default value. Previous: Fragments Next: Multipage apps forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
App_is_not_loading_when_running_remotely___Streaml.txt | App is not loading when running remotely - Streamlit Docs Documentation search Search rocket_launch Get started Installation add Fundamentals add First steps add code Develop Concepts add API reference add Tutorials add Quick reference add web_asset Deploy Concepts add Streamlit Community Cloud add Snowflake Other platforms add school Knowledge base FAQ Installing dependencies Deployment issues Home / Knowledge base / Deployment issues / App is not loading when running remotely App is not loading when running remotely Below are a few common errors that occur when users spin up their own solution to host a Streamlit app remotely. To learn about a deceptively simple way to host Streamlit apps that avoids all the issues below, check out Streamlit Community Cloud . Symptom #1: The app never loads When you enter the app's URL in a browser and all you see is a blank page, a "Page not found" error, a "Connection refused" error , or anything like that, first check that Streamlit is actually running on the remote server. On a Linux server you can SSH into it and then run: ps -Al | grep streamlit If you see Streamlit running, the most likely culprit is the Streamlit port not being exposed. The fix depends on your exact setup. Below are three example fixes: Try port 80: Some hosts expose port 80 by default. To set Streamlit to use that port, start Streamlit with the --server.port option: streamlit run my_app.py --server.port=80 AWS EC2 server : First, click on your instance in the AWS Console . Then scroll down and click on Security Groups → Inbound → Edit . Next, add a Custom TCP rule that allows the Port Range 8501 with Source 0.0.0.0/0 . Other types of server : Check the firewall settings. If that still doesn't solve the problem, try running a simple HTTP server instead of Streamlit, and seeing if that works correctly. If it does, then you know the problem lies somewhere in your Streamlit app or configuration (in which case you should ask for help in our forums !) If not, then it's definitely unrelated to Streamlit. How to start a simple HTTP server: python -m http.server [port] Symptom #2: The app says "Please wait..." or shows skeleton elements forever This symptom appears differently starting from version 1.29.0. For earlier versions of Streamlit, a loading app shows a blue box in the center of the page with a "Please wait..." message. Starting from version 1.29.0, a loading app shows skeleton elements. If this loading screen does not go away, the underlying cause is likely one of the following: Using port 3000 which is reserved for internal development. Misconfigured CORS protection. Server is stripping headers from the Websocket connection, thereby breaking compression. To diagnose the issue, first make sure you are not using port 3000. If in doubt, try port 80 as described above. Next, try temporarily disabling CORS protection by running Streamlit with the --server.enableCORS flag set to false : streamlit run my_app.py --server.enableCORS=false If this fixes your issue, you should re-enable CORS protection and then set browser.serverAddress to the URL of your Streamlit app. If the issue persists, try disabling websocket compression by running Streamlit with the --server.enableWebsocketCompression flag set to false streamlit run my_app.py --server.enableWebsocketCompression=false If this fixes your issue, your server setup is likely stripping the Sec-WebSocket-Extensions HTTP header that is used to negotiate Websocket compression. Compression is not required for Streamlit to work, but it's strongly recommended as it improves performance. If you'd like to turn it back on, you'll need to find which part of your infrastructure is stripping the Sec-WebSocket-Extensions HTTP header and change that behavior. Symptom #3: Unable to upload files when running in multiple replicas If the file uploader widget returns an error with status code 403, this is probably due to a misconfiguration in your app's XSRF protection logic. To diagnose the issue, try temporarily disabling XSRF protection by running Streamlit with the --server.enableXsrfProtection flag set to false : streamlit run my_app.py --server.enableXsrfProtection=false If this fixes your issue, you should re-enable XSRF protection and try one or both of the following: Set browser.serverAddress and browser.serverPort to the URL and port of your Streamlit app. Configure your app to use the same secret across every replica by setting the server.cookieSecret config option to the same hard-to-guess string everywhere. Previous: Invoking a Python subprocess in a deployed Streamlit app Next: Argh. This app has gone over its resource limits forum Still have questions? Our forums are full of helpful information and Streamlit experts. Home Contact Us Community © 2025 Snowflake Inc. Cookie policy forum Ask AI |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 67