Make a Timer with Streamlit
Streamlit is an open-source Python library that makes it easy to create and share beautiful, custom web apps for machine learning and data science. So if you don’t want to get into the complexities of web development, do try streamlit.
So We will create a simple Python Timer with Streamlit
- Install Streamlit
pip install streamlit
2. Define a python function count_down() that does the following
i. receives time in seconds ‘ts’
ii. convert ts to mins:secs format. Eg: 1510 seconds will be 25:10. display it
iii. Decrement ts after a delay of 1s
iv. Repeat step(ii) and (iii) in a while loop till ts is zero.
import time
def count_down(ts):
while ts:
mins, secs = divmod(ts, 60)
time_now = '{:02d}:{:02d}'.format(mins, secs)
print(f"{time_now}")
time.sleep(1)
ts -= 1
Now we can define the main function where we call this function.
import streamlit as st
In main() function,
- To get input from user use st.number_input() function. This will make sure that user enters a number as input. You can set the minimum value user should enter and a default value by setting min_value and value parameters as shown.
time_minutes = st.number_input('Enter the time in minutes ', min_value=1, value=25)
2. Convert this time in minutes to time in seconds
time_in_seconds = time_minutes * 60
3. Once we have time_in_seconds , we can call count_down function defined before. We call count_down when ‘START’ button is pressed. To do that we can use st.button() function as shown.
if st.button("START"):
count_down(int(time_in_seconds))
4. To display time in the web browser we need to make changes in count_down function as well. Replace print with st.header() function to display in time in big fonts. Also you can display ‘Time Up’ when time exhausts. I have also added
import streamlit as st
import timedef count_down(ts):
while ts:
mins, secs = divmod(ts, 60)
time_now = '{:02d}:{:02d}'.format(mins, secs)
st.header(f"{time_now}")
time.sleep(1)
ts -= 1 st.header("Time Up!")def main():
st.title("Pomodoro")
time_minutes = st.number_input('Enter the time in minutes ', min_value=1, value=25)
time_in_seconds = time_minutes * 60if st.button("FOCUS"):
count_down(int(time_in_seconds))if __name__ == '__main__':
main()
5. The above code will print time in new line as shown . But this is not exaclty what we want. We want to replace the previous time and overwrite with new time. To do that add st.empty() option in streamlit. This will empty the contents for every iteration of while loop.
import streamlit as st
import timedef count_down(ts):
with st.empty():
while ts:
mins, secs = divmod(ts, 60)
time_now = '{:02d}:{:02d}'.format(mins, secs)
st.header(f"{time_now}")
time.sleep(1)
ts -= 1st.write("Time Up!")def main():
st.title("Pomodoro")
time_minutes = st.number_input('Enter the time in minutes ', min_value=1, value=25)
time_in_seconds = time_minutes * 60if st.button("START"):
count_down(int(time_in_seconds))if __name__ == '__main__':
main()