search
HomeBackend DevelopmentPython TutorialStreamlit Part Mastering Layouts

Streamlit Part Mastering Layouts

Mastering Layouts in Streamlit: A Step-by-Step Guide

Streamlit, a widely-used framework for building interactive Python applications, particularly for data visualization, dashboards, and machine learning demos, stands out not only for its user-friendly nature but also for its ability to create visually appealing and intuitive layouts. In this blog post, we’ll guide you through a Python example that demonstrates how to effectively utilize layout elements such as columns, containers, placeholders, and more in Streamlit.

Let’s break down the layout techniques you can use to make your apps cleaner and more interactive.

Setting the Stage: Page Configuration

Before jumping into the layout elements, we configure the page using st.set_page_config(). This method allows you to customize the page title, icon, layout, and sidebar behavior right when the app loads.

st.set_page_config(
    page_title="Streamlit Layouts Tutorial",
    page_icon=":art:",
    layout="wide",
    initial_sidebar_state="collapsed",
)

Here, we give the page a title, set the layout to "wide" (which makes use of the full browser width), and collapse the sidebar initially for a cleaner look.

1. Structuring with Columns

One of the most powerful layout tools in Streamlit is columns. They allow you to display content side-by-side, giving a more organized and visually appealing look to your app.

st.header("Columns")
st.write("Using `st.columns()` to create columns.")

# Create two columns
col1, col2 = st.columns(2)

col1.write("This is column 1")
if col1.button("Button in Column 1"):
    col1.write("Button 1 pressed")

col2.write("This is column 2")
if col2.button("Button in Column 2"):
    col2.write("Button 2 pressed")

In this snippet, we create two columns and place buttons in each. The columns are split evenly, and any interactions within one column don’t affect the other.

Why Columns?

Columns are great for displaying related information side by side, such as data summaries, charts, or interactive controls.

2. Grouping with Containers

Next up is the container element. Containers in Streamlit allow you to group multiple elements together, making it easier to manage complex layouts.

st.header("Container")
st.write("Using `st.container()` to group elements together.")

with st.container():
    st.write("This is inside a container")
    st.button("Button inside container")

    # Nested container
    with st.container():
        st.write("This is a nested container")
        st.button("Button inside nested container")

In this example, the st.container() method wraps multiple elements (text and a button) together. You can even nest containers inside one another to create hierarchical layouts.

Why Containers?

Containers help maintain a clean and grouped structure, especially when dealing with multiple sections of content that belong together logically.

3. Dynamically Updating with Placeholders

A powerful feature of Streamlit is its ability to update content dynamically. This is done using st.empty(), which serves as a placeholder that you can update later.

st.header("Empty")
st.write("Using `st.empty()` as a placeholder for updating content.")

placeholder = st.empty()

# Update the placeholder content dynamically
for i in range(5):
    placeholder.write(f"Updating... {i}")
    time.sleep(1)

placeholder.write("Done!")

In this example, we use a for loop to update the placeholder with a new value every second. Once the loop is done, we replace the placeholder content with "Done!"

Why Use Placeholders?

Placeholders are ideal for situations where you need to update parts of your app dynamically without rerunning the entire app, such as live data feeds or progress updates.

4. Hiding and Showing with Expanders

Expandable sections are perfect for hiding advanced settings or additional information that you don’t want to clutter the main layout.

st.set_page_config(
    page_title="Streamlit Layouts Tutorial",
    page_icon=":art:",
    layout="wide",
    initial_sidebar_state="collapsed",
)

Here, we wrap some content and a button inside an expander, which users can click to reveal or hide the content.

Why Expanders?

Expanders help keep your interface clean by hiding less important or advanced options while still making them easily accessible when needed.

5. Creating Forms

Streamlit forms allow you to group input widgets together and wait for the user to submit them all at once, rather than reacting to each input individually.

st.header("Columns")
st.write("Using `st.columns()` to create columns.")

# Create two columns
col1, col2 = st.columns(2)

col1.write("This is column 1")
if col1.button("Button in Column 1"):
    col1.write("Button 1 pressed")

col2.write("This is column 2")
if col2.button("Button in Column 2"):
    col2.write("Button 2 pressed")

In this example, we use a form to collect a user’s name and age, and only once they click the submit button does Streamlit process the input.

Why Forms?

Forms ensure that input actions are grouped and submitted as a batch, which is ideal for cases like user registration or data filtering.

6. Adding a Sidebar

Sidebars are useful for navigation, app settings, or extra options that don’t clutter the main interface.

st.header("Container")
st.write("Using `st.container()` to group elements together.")

with st.container():
    st.write("This is inside a container")
    st.button("Button inside container")

    # Nested container
    with st.container():
        st.write("This is a nested container")
        st.button("Button inside nested container")

This code adds a button to the sidebar, which collapses by default but can be expanded by the user.

Why Use Sidebars?

Sidebars are perfect for secondary content like navigation links, filters, or app settings that are always accessible but don’t need to take up space in the main layout.

7. Navigating with Tabs

Tabs are a great way to organize content within a single section, allowing users to switch between different views without leaving the page.

st.header("Empty")
st.write("Using `st.empty()` as a placeholder for updating content.")

placeholder = st.empty()

# Update the placeholder content dynamically
for i in range(5):
    placeholder.write(f"Updating... {i}")
    time.sleep(1)

placeholder.write("Done!")

In this example, we use three tabs to display different content related to animals. Each tab is independent and contains its own content.

Why Tabs?

Tabs are ideal for organizing related content into sections, like different data views or categories of information, without requiring separate pages.

Conclusion

Mastering Streamlit's layout elements empowers you to create clean, interactive, and user-friendly applications. By skillfully using columns, containers, placeholders, expanders, forms, sidebars, and tabs, you can effectively organize your content and enhance the overall user experience. These tools allow you to craft intuitive interfaces that guide users through your application seamlessly.


? Get the Code: GitHub - jamesbmour/blog_tutorials
? Related Streamlit Tutorials:JustCodeIt
? Support my work: Buy Me a Coffee

The above is the detailed content of Streamlit Part Mastering Layouts. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment