Prof Arnold wrote this section in October 2022. Please send him any suggestions or questions!
Streamlit lets you make website-based user interfaces to your Python programs. The program can get input from text boxes or other widgets on the website and show output in the form of text, plots, or a variety of other formats.
Streamlit Upgrades input() and print() ¶
A basic greeting might look like this in plain Python:
name = input("Your name: ")
print("Hello, " + name)
To make this run on Streamlit, we replace input()
with st.text_input()
and print()
with st.write()
. We have to add an import for the streamlit module also.
# Shim to make "Run" in Thonny behave like "streamlit run this_file.py" on Terminal
import sys, streamlit.web.cli, streamlit.runtime.runtime
if '__file__' not in globals(): raise Exception("Save the file first!")
if not streamlit.runtime.runtime.Runtime.exists():
sys.argv[:] = ['streamlit', 'run', __file__]; sys.exit(streamlit.web.cli.main())
# End shim.
import streamlit as st
name = st.text_input("Your name: ")
st.write("Hello, " + name)
To run this code:
- Type it into Thonny as usual.
- Save the file (use
greet.py
; don’t usestreamlit.py
!) - Run the file as usual in Thonny.
- If you get an
ImportError
, follow the instructions for Additional Packages on the course Syllabus, then try again. - If you’re prompted to enter your email address, just leave it blank and press Enter/return.
- Accept any security warning that may pop up on some systems.
- A browser window should pop up now.
- If you get an
If for some reason something doesn’t work, you can use the following alternative method:
- On the Tools menu, choose “Open system shell”.
- Type the
streamlit run
command that was given in the error message (stop before the “[ARGUMENTS]” part) and press Enter. - If you are prompted for an email address, simply press Enter (you don’t need to provide one).
- Accept any security warning that may pop up on some systems.
- In a few moments you should see a new tab pop up in your web browser window.
Streamlit reruns your program when you change the code. ¶
In greet.py
, try changing the "Hello, " to "Greetings, " and Save the file. A message should pop up on the top-right of the browser tab, asking if you would like to Rerun or Always Rerun. I suggest you use Always Rerun.
Streamlit reruns your program when any input changes. ¶
In a program that uses input()
, the program stops when it reaches any input()
statement and continues only when an input is provided.
Streamlit is a little different:
- the first time your program is run, all inputs are given placeholder values.
- when an input changes, the program gets re-run from the top, with the new values.
Streamlit provides many different input widgets. ¶
See the documentation for a complete list of input widgets.. Try st.number_input()
, like this:
import streamlit as st
temp_F = st.number_input("Temp in F: ", step=0.1)
temp_C = (temp_F - 32) * 5 / 9
st.write("Temp in C is", temp_C)