일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 구현
- Level2_PStage
- 정렬
- dp
- 그리디
- 백준
- 파이썬 3
- 단계별문제풀이
- dfs
- 알고리즘_스터디
- 프로그래머스
- 이진탐색
- 개인회고
- 그래프이론
- ODQA
- U_stage
- mrc
- 주간회고
- 글또
- 부스트캠프_AITech_3기
- 다시보기
- Level1
- Level2
- python3
- 기술면접
- 부스트캠프_AITech3기
- 최단경로
- 알고리즘스터디
- 백트랙킹
- 이코테
- Today
- Total
국문과 유목민
[Ipywidget] Ipywidget 명령어 본문
ipywidgets는 주피터 노트북과 IPython 커널을 위한 대화형 HTML 위젯이다. 사용자는 ipywidgets을 사용해 자신의 데이터를 제어하고 데이터의 변화를 시각화할 수 있습니다. 주피터노트북에서 Voila로 프로토타입을 제작할 때 사용할 수도있으며, 이를 이용해 Interactive한 프로토타입을 만들어낼 수 있습니다.
ipywidgets에는 Numeric, Text, Boolean, Selection, Upload, Image, Date Picker Widget과 Widget Events, Interact Decorator, Layout 등의 기능이 있다. 해당 기능들에 대해 간단한 코드와 display된 결과를 간단히 적어두고자 한다. 더 자세한 widgets에 대한 사용법은 공식 Documents를 확인하기 바란다.
설치
설치는 어렵지 않고, pip나 conda를 이용해 설치할 수 있다.
# pip
pip install ipywidgets
# conda
conda install -c conda-forge ipywidgets
ipywidget Document: https://ipywidgets.readthedocs.io/en/latest/user_install.html
라이브러리 Import
import ipywidgets as widgets
from IPython.display import display
widget의 값은 변수에 할당할 수 있으며, 이렇게 할당된 변수는 display(변수명)를 활용해 시각화할 수 있다.
NumericWidgets
숫자값을 표시하게 설계된 위젯으로 Int, Float, FloatLog, IntRange, FloatRange가 존재한다. Slider는 값을 조절 할 수 있는 Bar를 의미한다. Range도 설정하 수 있으며, Range의 범위는 조절할 수 있다. Numeric Widges의 사용법은 거의 비슷하다. 변수.value를 하면 설정된 값을 볼 수 있다.
int_widget = widgets.IntSlider(
value=7,
min=0,
max=10,
step=1,
orientation='horizontal', # Vertical
description='Value:',
)
int_widget.value # 값을 볼 수 있다.
Text
Slider 형태가 아닌 Input Box 형태로 전달된다. Bounded가 들어간 함수는 범위 제한이 존재하고, Bounded가 없는 함수는 범위 제한이 없다는 특성이 있다. 역시 .value로 값에 접근이 가능하다.
widgets.IntText(
value=7,
description='Any:',
disabled=False
)
String widgets
Text를 입력할 수 있는 위젯으로 Text, Textarea, Password가 있다.
widgets.Text(
value='Hello World',
placeholder='Type something',
description='String:'
)
Boolean widgets
True, False를 표현할 수 있는 위젯으로, ToggleButton, Checkbox가 있다.
ToggleButton은 button_style(success, info, warning, danger)과 icon 등을 설정할 수 있으며, Checkbox는 들여쓰기 여부 설정이 가능하다.
widgets.ToggleButton(
value=False,
description='Click me',
button_style='', # 'success', 'info', 'warning', 'danger', ''
tooltip='Description',
icon='check' # FontAwesome에서 확인할 수 있음 : https://fontawesome.com/v4.7/icons/
)
widgets.Checkbox(
value=False,
description='Check me',
indent=True # Tab키 여부라고 생각
)
Selection widgets
선택을 할 수 있는 위젯이다. Dropdown, RadioButtons이 있다.
Drodown과 RadioButtons은 options를 리스트와 dict형태로 넣어줄 수도 있다. 만약 dict형태로 넣는다면, 표시는 key값으로 되지만, 실제 입력은 Value로 받아올 수 있다.
widgets.Dropdown(
options=['1', '2', '3'],
value='2',
description='Number:',
disabled=False,
)
widgets.RadioButtons(
options=['pepperoni', 'pineapple', 'anchovies'],
description='Topping:',
)
Upload Widget
FileUpload: 파일을 업로드하기 위한 위젯이다. accept(허용할 확장자), multiple(여러 파일을 업로드 하고 싶으면 True, 단일 파일은 False)
widgets.FileUpload(
accept='', # 허용할 확장자
multiple=False # 여러 파일을 업로드하고 싶으면 True, 단일 파일은 False
)
Image: 이미지 파일을 업로드하기 위한 위젯이다.
file = open("image.png", "rb")
image = file.read()
widgets.Image(
value=image,
format='png',
width=300,
height=400,
)
Date Picker Widget
DatePicker: Date를 정하기 위한 위젯이다. 오늘 날짜를 기준으로 데이터를 선택할 수 있다.
widgets.DatePicker(
description='Pick a Date',
disabled=False
)
Interact Decorator
@interact 데코레이터를 사용하면 UI 컨트롤러가 생성된다. 함수의 인자를 받아서 UI가 생성되기 때문에 만약 함수의 인자 중 하나를 고정하고 싶거나, UI에서 나타나는 것을 원하지 않는 경우 fixed를 사용할 수 있다.
from ipywidgets import interact
@interact(x=True, y=1.0)
def g(x, y):
return (x, y)
Widget Events
위젯에서 특정 이벤트가 발생했을 때, 어떤 동작이 발생하길 원하는 경우에 사용한다. 주로 on_click이나 observe를 활용한다.
on_click함수: 버튼이 클릭되었을 때 특정 작업을 하고 싶은 경우 on_click에 함수를 넘겨주면 된다.
button = widgets.Button(description="Click Me!")
output = widgets.Output()
display(button, output)
def on_button_clicked(button):
with output:
print("Hello world!")
button.on_click(on_button_clicked)
observe 함수: 위젯의 속성이 변경될 때 업데이트해주는 위젯이다.
int_range = widgets.IntSlider()
output2 = widgets.Output()
display(int_range, output2)
def on_value_change(change):
with output2:
print(change['new'])
int_range.observe(on_value_change, names='value')
Layout
위젯의 레이아웃을 구성하고 싶은 경우 HBox, VBox를 사용할 수 있다. 여러 개 클릭하고 싶은 버튼을 만들고 싶다면 이를 활용할 수 있다.
from ipywidgets import Button, HBox, VBox
words = ['correct', 'horse', 'battery', 'staple']
items = [Button(description=w) for w in words]
left_box = VBox([items[0], items[1]])
right_box = VBox([items[2], items[3]])
HBox([left_box, right_box])
'IT 견문록 > ProductServing' 카테고리의 다른 글
[FastAPI] FastAPI 기초 지식 (0) | 2022.05.25 |
---|---|
[Backend] 백엔드 기초 지식 (0) | 2022.05.24 |
[Streamlit] Streamlit 명령어 (0) | 2022.05.18 |