Skip to content

Instantly share code, notes, and snippets.

@asehmi
Created May 24, 2022 11:01
Show Gist options
  • Save asehmi/60242982c5e1626203e34cc37e9d7d34 to your computer and use it in GitHub Desktop.
Save asehmi/60242982c5e1626203e34cc37e9d7d34 to your computer and use it in GitHub Desktop.
Using Streamlit widgets in a multi-column table format
# My solution for: https://discuss.streamlit.io/t/how-to-update-st-columns/25501/3
# This uses a button callback to report the enroll action. Notice how all the widget keys are
# generated so they are unique. To deal with being able to edit the values from their defaults,
# and report on them correctly, I am printing out the widgets’ session state values.
import streamlit as st
from dataclasses import dataclass
state = st.session_state
@dataclass
class Student():
def __init__(self, name, age, course):
self.name = name
self.age = age
self.course = course
def get_students():
return [
Student(name='Student A', age=20, course='CS101'),
Student(name='Student B', age=21, course='CS101'),
Student(name='Student C', age=23, course='DS101'),
Student(name='Student D', age=18, course='DS101'),
Student(name='Student E', age=19, course='CS101'),
]
def _enroll_cb(student, index):
name = state[f'{student.name}_{index}']
age = state[f'{student.age}_{index}']
course = state[f'{student.course}_{index}']
st.info(f'Enrolled: {name}, {age}, {course}')
c1, c2, c3, c4 = st.columns([1,1,1,1])
c1.subheader('Student')
c2.subheader('Age')
c3.subheader('Course')
c4.subheader(' ')
for index, student in enumerate(get_students(), start=0):
with c1:
st.text_input('', student.name, key=f'{student.name}_{index}')
with c2:
st.number_input('', min_value=18, max_value=60, value=student.age, key=f'{student.age}_{index}')
with c3:
st.text_input('', student.course, key=f'{student.course}_{index}')
with c4:
st.write(' ')
st.button('enroll', on_click=_enroll_cb, args=(student,index), key= f'enroll_{index}')
@asehmi
Copy link
Author

asehmi commented May 24, 2022

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment