>  기사  >  백엔드 개발  >  효율적인 부품 마스터링 입력 위젯

효율적인 부품 마스터링 입력 위젯

Patricia Arquette
Patricia Arquette원래의
2024-09-25 06:25:14209검색

Streamlit Part Mastering Input Widgets

Streamlit에서 입력 위젯 마스터하기: 종합 가이드

? 코드 받기: GitHub - jamesbmour/blog_tutorials

? 관련 Streamlit 튜토리얼:JustCodeIt

Streamlit은 Python을 사용하여 웹 애플리케이션을 만드는 방식에 혁명을 일으켰습니다. 단순성과 성능 덕분에 데이터 과학자와 개발자 모두에게 탁월한 선택이 됩니다. 이번 포스팅에서는 Streamlit의 가장 강력한 기능 중 하나인 입력 위젯에 대해 자세히 살펴보겠습니다. 16가지 다양한 입력 유형을 살펴보고 이를 Streamlit 앱에서 효과적으로 사용하는 방법을 보여드리겠습니다.

Streamlit 앱 설정

위젯을 살펴보기 전에 Streamlit 앱을 설정해 보겠습니다.

import streamlit as st

st.set_page_config(layout="wide")
st.title("Streamlit Part 4: Inputs in Streamlit")

col1, col2 = st.columns(2)

Streamlit을 가져오고, 페이지를 넓은 레이아웃으로 설정하고, 제목을 추가하고, 더 나은 위젯 구성을 위해 두 개의 열을 만들었습니다.

버튼 입력

1. 기본 버튼

가장 간단한 입력 형태는 버튼입니다. 만드는 방법은 다음과 같습니다.

with col1:
    st.subheader("1. Button")
    btn1 = st.button("Click Me", key="button", help="Click me to see the magic", type='secondary', disabled=False)
    if btn1:
        st.write("Button Clicked")

자세한 설명:

  • st.button() 함수는 클릭 가능한 버튼을 생성합니다.
  • 키: 버튼의 고유 식별자로, 버튼이 여러 개 있을 때 유용합니다.
  • 도움말: 버튼 위에 마우스를 올리면 나타나는 도구 설명 텍스트입니다.
  • 유형: 버튼의 모양을 결정합니다('기본', '보조' 등).
  • 비활성화됨: True로 설정하면 버튼이 회색으로 표시되어 클릭할 수 없게 됩니다.

사용 사례:

  • 데이터 처리 또는 모델 훈련 트리거
  • 양식 제출
  • 데이터 또는 차트 새로고침

팁: 버튼 상태를 사용하여 섹션 표시/숨기기, 계산 트리거 등 앱의 흐름을 제어하세요.

2. 링크 버튼

사용자를 외부 링크로 리디렉션하려면 링크 버튼을 사용하세요.

st.subheader("2. Link Button")
if st.link_button("Click Me", "<https://www.streamlit.io/>"):
    st.write("Link Button Clicked")

자세한 설명:

  • st.link_button()은 클릭 시 지정된 URL이 있는 새 탭을 여는 버튼을 생성합니다.
  • 첫 번째 인수는 버튼 텍스트이고 두 번째 인수는 URL입니다.

사용 사례:

  • 문서 또는 외부 리소스 링크
  • 소셜 미디어 프로필로 리디렉션
  • 관련 웹 애플리케이션 연결

팁: 사용자가 불필요하게 앱에서 멀어지는 것을 방지하려면 링크 버튼을 아껴서 사용하세요.

3. 다운로드 버튼

사용자가 앱에서 직접 파일을 다운로드할 수 있도록 허용:

st.subheader("3. Download Button")
if st.download_button("Download Me", "hello world", "hello.txt", mime='text/plain'):
    st.write("Download Button Clicked")

자세한 설명:

  • st.download_button()은 클릭 시 파일 다운로드를 트리거하는 버튼을 생성합니다.
  • 인수: 버튼 레이블, 파일 콘텐츠, 파일 이름 및 MIME 유형.
  • MIME 유형은 파일 유형을 지정합니다(예: .txt의 경우 'text/plain', .pdf의 경우 'application/pdf').

사용 사례:

  • 생성된 보고서 또는 데이터 다운로드
  • 처리된 이미지 또는 차트 저장
  • 사용자 제작 콘텐츠 내보내기

팁: 사용자 상호 작용이나 데이터 처리 결과를 기반으로 파일 콘텐츠를 동적으로 생성할 수 있습니다.

선택 위젯

4. 체크박스

체크박스는 옵션을 전환하는 데 유용합니다.

st.subheader("4. Checkbox")
checkbox_val = st.checkbox("Check Me", value=False)
if checkbox_val:
    st.write("Checkbox Checked")

자세한 설명:

  • st.checkbox()는 토글 가능한 체크박스를 생성합니다.
  • 값 매개변수는 초기 상태(True/False)를 설정합니다.

사용 사례:

  • 앱 기능 활성화/비활성화
  • 목록에서 여러 옵션 선택
  • 간단한 예/아니요 질문 만들기

팁: 더욱 역동적인 사용자 경험을 위해 체크박스를 사용하여 앱의 다른 요소 표시 여부를 제어하세요.

5. 라디오 버튼

사용자가 목록에서 하나의 옵션을 선택해야 하는 경우:

st.subheader("5. Radio")
radio_val = st.radio("Select Color", ["Red", "Green", "Blue"], index=0)
if radio_val:
    st.write(f"You selected {radio_val}")

자세한 설명:

  • st.radio()는 라디오 버튼 세트를 생성합니다.
  • 첫 번째 인수는 레이블이고 그 뒤에 옵션 목록이 옵니다.
  • 인덱스는 기본 선택 옵션(0부터 시작)을 지정합니다.

사용 사례:

  • 상호 배타적인 옵션 중에서 선택
  • 앱 모드 또는 테마 설정
  • 카테고리 기준으로 데이터 필터링

팁: 상호 배타적인 옵션이 적은 경우(보통 2~5개) 라디오 버튼을 사용하세요.

6. 선택 상자

드롭다운 선택:

st.subheader("6. Selectbox")
select_val = st.selectbox("Select Color", ["Red", "Green", "Blue", "Black"], index=1)
if select_val:
    st.write(f"You selected {select_val}")

자세한 설명:

  • st.selectbox()는 드롭다운 메뉴를 생성합니다.
  • 라디오 버튼과 유사하지만 더 긴 옵션 목록에 더 좋습니다.
  • index는 기본 선택 옵션을 설정합니다.

사용 사례:

  • Selecting from a long list of options
  • Choosing categories or filters
  • Setting parameters for data analysis

Tip: You can populate the options dynamically based on data or user inputs.

7. Multi-select

Allow users to select multiple options:

st.subheader("7. Multiselect")
multiselect_val = st.multiselect("Select Colors", ["Red", "Green", "Blue", "Black"], default=["Red"])
if multiselect_val:
    st.write(f"You selected {multiselect_val}")

Detailed Explanation:

  • st.multiselect() creates a dropdown that allows multiple selections.
  • default sets the initially selected options.

Use Cases:

  • Selecting multiple filters for data
  • Choosing features for a machine learning model
  • Creating customizable dashboards

Tip: Use st.multiselect() when you want users to be able to select any number of options, including none or all.

8. Select Slider

For selecting from a range of discrete values:

st.subheader("8. Select Slider")
select_slider_val = st.select_slider("Select Value", options=range(1, 101), value=50)
if select_slider_val:
    st.write(f"You selected {select_slider_val}")

Detailed Explanation:

  • st.select_slider() creates a slider with discrete values.
  • options can be a range of numbers or a list of any values (even strings).
  • value sets the initial position of the slider.

Use Cases:

  • Selecting from a range of predefined values
  • Creating rating systems
  • Adjusting parameters with specific increments

Tip: You can use custom labels for the slider by passing a list of tuples (label, value) as options.

Text Inputs

9. Text Input

For single-line text input:

with col2:
    st.subheader("9. Text Input")
    text_input_val = st.text_input("Enter some text", value="", max_chars=50)
    if text_input_val:
        st.write(f"You entered {text_input_val}")

Detailed Explanation:

  • st.text_input() creates a single-line text input field.
  • value sets the initial text (if any).
  • max_chars limits the number of characters that can be entered.

Use Cases:

  • Getting user names or short responses
  • Inputting search queries
  • Entering simple parameters or values

Tip: Use the type parameter to create password fields or other specialized inputs.

10. Text Area

For multi-line text input:

st.subheader("10. Text Area")
text_area_val = st.text_area("Enter some text", value="", height=150, max_chars=200)
if text_area_val:
    st.write(f"You entered {text_area_val}")

Detailed Explanation:

  • st.text_area() creates a multi-line text input box.
  • height sets the vertical size of the box.
  • max_chars limits the total character count.

Use Cases:

  • Collecting longer text responses or comments
  • Inputting multi-line code snippets
  • Creating text-based data entry forms

Tip: You can use st.text_area() with natural language processing models for text analysis or generation tasks.

Numeric and Date/Time Inputs

11. Number Input

For numerical inputs:

st.subheader("11. Number Input")
number_input_val = st.number_input("Enter a number", value=0, min_value=0, max_value=100, step=1)
if number_input_val:
    st.write(f"You entered {number_input_val}")

Detailed Explanation:

  • st.number_input() creates a field for numerical input.
  • min_value and max_value set the allowed range.
  • step defines the increment/decrement step.

Use Cases:

  • Inputting quantities or amounts
  • Setting numerical parameters for algorithms
  • Creating age or rating inputs

Tip: You can use format parameter to control the display of decimal places.

12. Date Input

For selecting dates:

st.subheader("12. Date Input")
date_input_val = st.date_input("Enter a date")
if date_input_val:
    st.write(f"You selected {date_input_val}")

Detailed Explanation:

  • st.date_input() creates a date picker widget.
  • You can set min_value and max_value to limit the date range.

Use Cases:

  • Selecting dates for data filtering
  • Setting deadlines or event dates
  • Inputting birthdates or other significant dates

Tip: Use datetime.date.today() as the default value to start with the current date.

13. Time Input

For selecting times:

st.subheader("13. Time Input")
time_input_val = st.time_input("Enter a time")
if time_input_val:
    st.write(f"You selected {time_input_val}")

Detailed Explanation:

  • st.time_input() creates a time picker widget.
  • Returns a datetime.time object.

Use Cases:

  • Setting appointment times
  • Configuring schedules
  • Inputting time-based parameters

Tip: Combine with st.date_input() to create full datetime inputs.

Advanced Inputs

14. File Uploader

For uploading files:

st.subheader("14. File Uploader")
file_uploader_val = st.file_uploader("Upload a file", type=["png", "jpg", "txt"])
if file_uploader_val:
    st.write(f"You uploaded {file_uploader_val.name}")

Detailed Explanation:

  • st.file_uploader() creates a file upload widget.
  • type parameter limits the allowed file types.
  • Returns a UploadedFile object that you can process.

Use Cases:

  • Uploading images for processing
  • Importing data files for analysis
  • Allowing users to upload documents or media

Tip: Use st.file_uploader() in combination with libraries like Pillow or pandas to process uploaded files directly in your app.

15. Color Picker

For selecting colors:

st.subheader("15. Color Picker")
color_picker_val = st.color_picker("Pick a color", value="#00f900")
if color_picker_val:
    st.write(f"You picked {color_picker_val}")

Detailed Explanation:

  • st.color_picker() creates a color selection widget.
  • Returns the selected color as a hex string.

Use Cases:

  • Customizing UI elements
  • Selecting colors for data visualization
  • Creating design tools

Tip: You can use the selected color to dynamically update the appearance of other elements in your app.

16. Camera Input

For capturing images using the device's camera:

st.subheader("16. Camera Input")
camera_input_val = st.camera_input("Take a picture", help="Capture an image using your camera")
if camera_input_val:
    st.write("Picture captured successfully")

Detailed Explanation:

  • st.camera_input() creates a widget that accesses the user's camera.
  • Returns an image file that can be processed or displayed.

Use Cases:

  • Real-time image processing applications
  • Document scanning features
  • Interactive computer vision demos

Tip: Combine with image processing libraries like OpenCV to perform real-time analysis on captured images.

Conclusion

Streamlit's input widgets provide a powerful and flexible way to create interactive web applications. From simple buttons to complex file uploaders and camera inputs, these widgets cover a wide range of use cases. By mastering these input types, you can create rich, interactive Streamlit apps that engage users and provide meaningful interactions with your data and models.

Happy Streamlit coding!

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

위 내용은 효율적인 부품 마스터링 입력 위젯의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.