Build GUI’s In Python Using StreamLit

There are many different ways to build a GUI (front end) in Python, but one of my favorite apps is Streamlit! It allows you to build web apps using pretty much nothing except Python, the apps have a lot of functionality with modern visuals, so let’s get started!

Installation

First off, we will need to install Streamlit, in order to do so we can use pip install, if you don’t have pip, read this article I made that shows how to install it. run this following command inside of your terminal / command prompt:

pip install streamlit

Awesome, once installed we are ready to go!

Let’s build a GUI!

Before building the GUI, let me break down the process:

First, we build out the app in Python > we then execute the code using streamlits function in our terminal / command prompt > then our web browser will open the streamlit app

To begin, let’s open a blank Python script, streamlit mentions in their beginning tutorial “first_app.py” but you can name it whatever you want, we then want to import the following packages:

import streamlit as st
import numpy as np
import pandas as pd
import time

These are the only packages we need to build a basic GUI for now, next off let’s name our app, we do so with the following line:

st.title('My first app')

We can also write out a standard line by using this statement:

st.write("WRITE THE TEXT HERE")

Next up, let’s use that knowledge to build out a table with a sentence describing what we’re doing, we do that by using the following lines:

st.write("Here's our first attempt at using data to create a table:")
st.write(pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
}))

At this point, we have a GUI that looks like this:

Awesome! Streamlit also has a very cool built in function which makes it a bit easier to build out a GUI, this method is called “Magic”. Without using the streamlit commands as mentioned above, the below script will also output the same result as above!

"""
# My first app
Here's our first attempt at using data to create a table:
"""

df = pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
})
df

Great! Next up, let’s output our own chart in this GUI, in this example we’re using a dataset of different numbers, but feel free to use your own datasets if needed:

chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])

st.line_chart(chart_data)

This output would essentially be this in the GUI:

We can also add a map to this specific GUI as well by using the following commands:

map_data = pd.DataFrame(
np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
columns=['lat', 'lon'])

st.map(map_data)

The output would be this:

You can probably begin to see how easy it is to pretty much build a web app using stream lit, but there is alot more you can do with this program. You can also add some customizability within your front end, for example, let’s say we wanted to get someones input, we could use the following lines of code to do so:

option = st.sidebar.selectbox(
'Which number do you like best?',
df['first column'])

'You selected:', option
left_column, right_column = st.beta_columns(2)
pressed = left_column.button('Press me?')
if pressed:
right_column.write("Woohoo!")

expander = st.beta_expander("FAQ")
expander.write("Here you could put in some really, really long explanations...")

This output would essentially be this:

Streamlit also mentions in their tutorial that you can add a progress bar as well into the program, this is how to do so in this example:

'Starting a long computation...'

# Add a placeholder
latest_iteration = st.empty()
bar = st.progress(0)

for i in range(100):
# Update the progress bar with each iteration.
latest_iteration.text(f'Iteration {i+1}')
bar.progress(i + 1)
time.sleep(0.1)

'...and now we\'re done!'

This essentially prints out this:

Awesome! This is the final code of our entire project:

import streamlit as st
# To make things easier later, we're also importing numpy and pandas for
# working with sample data.
import numpy as np
import pandas as pd
import time

st.title('My first app')

st.write("Here's our first attempt at using data to create a table:")
st.write(pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
}))
"""
# My first app
Here's our first attempt at using data to create a table:
"""

df = pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
})

df

chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])

st.line_chart(chart_data)

map_data = pd.DataFrame(
np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
columns=['lat', 'lon'])

st.map(map_data)

if st.checkbox('Show dataframe'):
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])

st.line_chart(chart_data)

option = st.selectbox(
'Which number do you like best?',
df['first column'])

'You selected: ', option

left_column, right_column = st.beta_columns(2)
pressed = left_column.button('Press me?')
if pressed:
right_column.write("Woohoo!")

expander = st.beta_expander("FAQ")
expander.write("Here you could put in some really, really long explanations...")

'Starting a long computation...'

# Add a placeholder
latest_iteration = st.empty()
bar = st.progress(0)

for i in range(100):
# Update the progress bar with each iteration.
latest_iteration.text(f'Iteration {i+1}')
bar.progress(i + 1)
time.sleep(0.1)

'...and now we\'re done!'

However, we aren’t done yet, we still have to run the code!

Running The Project

Running a streamlit project is a little bit different than running a standard Python project, we have to run this project using the streamlit command in our terminal / command prompt. To do so, first save your Python file & get the directory of that file. Next, let’s make our way to our terminal / command prompt and use the following streamlit command:

streamlit run DIRECTORY TO YOUR PYTHON FILE/file.py

Once we run that in our Terminal, we should see our terminal open the streamlit command option and open up a web page in our default web browser, we then will see our web browser get populated with our streamlit code, here is what the finished project should look like:

Congrats! You have just built your first Streamlit Python GUI! I will probably have a lot of tutorials that bounce off this specific article so I would definitely recommend reading more into streamlit! Enjoy building GUI’s with this tool!

Data Scientist / Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store