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:></https:>"): 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

2 시간 이내에 Python의 기본 프로그래밍 개념과 기술을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우기, 2. 마스터 제어 흐름 (조건부 명세서 및 루프), 3. 기능의 정의 및 사용을 이해하십시오. 4. 간단한 예제 및 코드 스 니펫을 통해 Python 프로그래밍을 신속하게 시작하십시오.

Python은 웹 개발, 데이터 과학, 기계 학습, 자동화 및 스크립팅 분야에서 널리 사용됩니다. 1) 웹 개발에서 Django 및 Flask 프레임 워크는 개발 프로세스를 단순화합니다. 2) 데이터 과학 및 기계 학습 분야에서 Numpy, Pandas, Scikit-Learn 및 Tensorflow 라이브러리는 강력한 지원을 제공합니다. 3) 자동화 및 스크립팅 측면에서 Python은 자동화 된 테스트 및 시스템 관리와 같은 작업에 적합합니다.

2 시간 이내에 파이썬의 기본 사항을 배울 수 있습니다. 1. 변수 및 데이터 유형을 배우십시오. 이를 통해 간단한 파이썬 프로그램 작성을 시작하는 데 도움이됩니다.

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

Python 3.6에 피클 파일로드 3.6 환경 보고서 오류 : modulenotfounderror : nomodulename ...

경치 좋은 스팟 댓글 분석에서 Jieba Word 세분화 문제를 해결하는 방법은 무엇입니까? 경치가 좋은 스팟 댓글 및 분석을 수행 할 때 종종 Jieba Word 세분화 도구를 사용하여 텍스트를 처리합니다 ...

정규 표현식을 사용하여 첫 번째 닫힌 태그와 정지와 일치하는 방법은 무엇입니까? HTML 또는 기타 마크 업 언어를 다룰 때는 정규 표현식이 종종 필요합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

Dreamweaver Mac版
시각적 웹 개발 도구

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

뜨거운 주제



