반응형

ipywidgets은 Jupyter Notebook과 JupyterLab 내에서 데이터 분석 및 시각화를 위해 다양한 widgets를 제공합니다. ipywidgets의 개념과 설치방법은 링크된 페이지에서 확인 가능합니다.

widget 형식 widget
Numeric widgets IntSlider, FloatSlider, FloatLogSlider, IntRangeSlider, FloatRangeSlider, IntProgress, FloatProgress, BoundedIntText, BoundedFloatText, IntText, FloatText
Boolean widgets ToggleButton, Checkbox, Valid
Selection widgets Dropdown, RadioButtons, Select, SelectionSlider, SelectionRangeSlider, ToggleButtons, SelectMultiple
String widget Text, Textarea, Combobox, Password, Label, HTML, HTML Math
Image  
Button  
Play (Animation) widget  
Tags input widget  
Date picker  
Time picker  
Datetime picker  
Color picker  
Container/Layout widgets Box, HBox, VBox, GridBox, Accordion, Tabs, Stacked

import ipywidgets as widgets

Numeric widgets

Numeric widgets은 사용자가 숫자 값을 입력하거나 선택할 수 있는 widget 유형입니다. 최소값, 최대값, 단계 크기 등과 같은 숫자 매개변수를 입력하거나 조정하는 방법을 제공합니다.

슬라이더는 초기값은 value으로 설정합니다. 하한 및 상한은 min  max로 정의되며 값은 step 매개변수에 따라 증가할 수 있습니다.

IntSlider

widgets.IntSlider(
    value=7,
    min=0,
    max=10,
    step=1,
    description='Test:',
    disabled=False,
    continuous_update=False,
    orientation='horizontal',
    readout=True,
    readout_format='d'
)

IntSlider

FloatSlider

widgets.FloatSlider(
    value=7.5,
    min=0,
    max=10.0,
    step=0.1,
    description='Test:',
    disabled=False,
    continuous_update=False,
    orientation='horizontal',
    readout=True,
    readout_format='.1f',
)

FloatSlider

orientation 매개변수를 'vertical'로 설정하면 수직 슬라이더로 widget을 만듭니다

widgets.FloatSlider(
    value=7.5,
    min=0,
    max=10.0,
    step=0.1,
    description='Test:',
    disabled=False,
    continuous_update=False,
    orientation='vertical',
    readout=True,
    readout_format='.1f',
)

더보기

추가로 CSS를 이용하여 수직 슬라이더를 만들 수 있습니다.

slider = widgets.FloatSlider(
    value=0.5,
    min=0,
    max=1.0,
    step=0.1,
    orientation='vertical',
    layout=widgets.Layout(width='auto', height='200px'),
)

slider.style.transform = 'rotate(270deg)'

FloatLogSlider

widgets.FloatLogSlider(
    value=10,
    base=10,
    min=-10, # max exponent of base
    max=10, # min exponent of base
    step=0.2, # exponent step
    description='Log Slider'
)

FloatLogSlider

IntRangeSlider

widgets.IntRangeSlider(
    value=[5, 7],
    min=0,
    max=10,
    step=1,
    description='Test:',
    disabled=False,
    continuous_update=False,
    orientation='horizontal',
    readout=True,
    readout_format='d',
)

IntRangeSlider

FloatRangeSlider

widgets.FloatRangeSlider(
    value=[5, 7.5],
    min=0,
    max=10.0,
    step=0.1,
    description='Test:',
    disabled=False,
    continuous_update=False,
    orientation='horizontal',
    readout=True,
    readout_format='.1f',
)

FloatRangeSlider

IntProgress

import time

int_prog_w = widgets.IntProgress(
    value=0,
    min=0,
    max=10,
    description='Loading:',
    bar_style='', # 'success', 'info', 'warning', 'danger' or ''
    style={'bar_color': 'maroon'},
    orientation='horizontal'
)

display(int_prog_w)

count = 0
while count <= 10:
    int_prog_w.value += 1 # signal to increment the progress bar
    time.sleep(0.1)
    count += 1

int_prog_w.description = 'Complete'

IntProgress

FloatProgress

float_prog_w = widgets.FloatProgress(
    value=0.0,
    min=0,
    max=10.0,
    description='Loading:',
    bar_style='info',
    style={'bar_color': '#ffff00'},
    orientation='horizontal'
)

display(float_prog_w)

count = 0
while count <= 10:
    float_prog_w.value += 1 # signal to increment the progress bar
    time.sleep(0.1)
    count += 1

float_prog_w.description = 'Complete'

FloatProgress

BoundedIntText

widgets.BoundedIntText(
    value=7,
    min=0,
    max=10,
    step=1,
    description='Text:',
    disabled=False
)

BoundedIntText

BoundedFloatText

widgets.BoundedFloatText(
    value=7.5,
    min=0,
    max=10.0,
    step=0.1,
    description='Text:',
    disabled=False
)

BoundedFloatText

IntText

widgets.IntText(
    value=7,
    description='Any:',
    disabled=False
)

IntText

FloatText

widgets.FloatText(
    value=7.5,
    description='Any:',
    disabled=False
)

FloatText


Boolean widgets

사용자가 Boolean 값(True 또는 False)을 선택할 수 있는 widget 유형입니다. 

ToggleButton

button_w = widgets.ToggleButton(
    value=False,
    description='Click me',
    disabled=False,
    button_style='', # 'success', 'info', 'warning', 'danger' or ''
    tooltip='Description',
    icon='check' # (FontAwesome names without the `fa-` prefix)
)

def on_click(change):
    print('clicked')

button_w.observe(on_click, 'value')
display(button_w)

ToggleButton

Checkbox

widgets.Checkbox(
    value=False,
    description='Check me',
    disabled=False,
    indent=False
)

Checkbox

Valid

widgets.Valid(
    value=False,
    description='Valid!',
)

Valid


Selection widgets

사용자가 미리 정의된 선택 목록에서 하나 이상의 옵션을 선택할 수 있는 widget 유형입니다. 어떠한 범주에서 값을 선택하거나 특정 기준으로 데이터를 필터링하기 위한 방법으로 사용됩니다.

Dropdown

widgets.Dropdown(
    options=['1', '2', '3'],
    value='2',
    description='Number:',
    disabled=False,
)

Dropdown 1

widgets.Dropdown(
    options=[('One', 1), ('Two', 2), ('Three', 3)],
    value=2,
    description='Number:',
)

Dropdown 2

RadioButtons

widgets.RadioButtons(
    options=['left', 'center', 'right'],
#    value='center', # Defaults to 'center'
#    layout={'width': 'max-content'}, # If the items' names are long
    description='Align:',
    disabled=False
)

RadioButtons

With dynamic layout and very long labels

widgets.Box(
    [
        widgets.Label(value='Pizza topping with a very long label:'),
        widgets.RadioButtons(
            options=[
                'pepperoni',
                'pineapple',
                'anchovies',
                'and the long name that will fit fine and the long name that will fit fine and the long name that will fit fine '
            ],
            layout={'width': 'max-content'}
        )
    ]
)

With dynamic layout and very long labels

Select

widgets.Select(
    options=['Linux', 'Windows', 'macOS'],
    value='macOS',
    # rows=10,
    description='OS:',
    disabled=False
)

Select

SelectionSlider

widgets.SelectionSlider(
    options=['scrambled', 'sunny side up', 'poached', 'over easy'],
    value='sunny side up',
    description='I like my eggs ...',
    disabled=False,
    continuous_update=False,
    orientation='horizontal',
    readout=True
)

SelectionSlider

SelectionRangeSlider

import datetime
dates = [datetime.date(2015, i, 1) for i in range(1, 13)]
options = [(i.strftime('%b'), i) for i in dates]
widgets.SelectionRangeSlider(
    options=options,
    index=(0, 11),
    description='Months (2015)',
    disabled=False
)

SelectionRangeSlider

ToggleButtons

widgets.ToggleButtons(
    options=['Slow', 'Regular', 'Fast'],
    description='Speed:',
    disabled=False,
    button_style='', # 'success', 'info', 'warning', 'danger' or ''
    tooltips=['Description of slow', 'Description of regular', 'Description of fast'],
#     icons=['check'] * 3
)

ToggleButtons

SelectMultiple

widgets.SelectMultiple(
    options=['Apples', 'Oranges', 'Pears'],
    value=['Oranges'],
    #rows=10,
    description='Fruits',
    disabled=False
)

SelectMultiple


String widgets

텍스트 문자열을 입력하거나 편집할 수 있는 widget 유형입니다.

Text

widgets.Text(
    value='Hello World',
    placeholder='Type something',
    description='String:',
    disabled=False
)

Textarea

widgets.Textarea(
    value='Hello World',
    placeholder='Type something',
    description='String:',
    disabled=False
)

Combobox

widgets.Combobox(
    # value='John',
    placeholder='Choose Someone',
    options=['Paul', 'John', 'George', 'Ringo'],
    description='Combobox:',
    ensure_option=True,
    disabled=False
)

Combobox

Password

widgets.Password(
    value='password',
    placeholder='Enter password',
    description='Password:',
    disabled=False
)

Password

Label

widgets.HBox([widgets.Label(value="The $m$ in $E=mc^2$:"), widgets.FloatSlider()])

HTML

widgets.HTML(
    value="Hello <b>World</b>",
    placeholder='Some HTML',
    description='Some HTML',
)

HTML Math

widgets.HTMLMath(
    value=r"Some math and <i>HTML</i>: \(x^2\) and $$\frac{x+1}{x-1}$$",
    placeholder='Some HTML',
    description='Some HTML',
)


Image

이미지를 표시하는 데 사용되며  PNG, JPEG, GIF 등 다양한 이미지 형식을 지원합니다.

file = open("asset/images/test_image.jpg", "rb")
image = file.read()
widgets.Image(
    value=image,
    format='png',
    width=300,
    height=400,
)


Button

사용자가 클릭하여 기능이나 작업을 트리거할 수 있는 버튼을 만드는 데 사용됩니다. 버튼의 텍스트, 설명, 아이콘 등 속성을 이용하여 버튼을 정의할 수 있습니다.

button = widgets.Button(
    description='Click me',
    disabled=False,
    button_style='', # 'success', 'info', 'warning', 'danger' or ''
    tooltip='Click me',
    icon='check' # (FontAwesome names without the `fa-` prefix)
)
button


Play (Animation) widget

사용자가 제어할 수 있는 애니메이션을 만드는 데 사용됩니다.

play = widgets.Play(
    value=50,
    min=0,
    max=100,
    step=1,
    interval=500,
    description="Press play",
    disabled=False
)
slider = widgets.IntSlider()
widgets.jslink((play, 'value'), (slider, 'value'))
widgets.HBox([play, slider])


Tag widgets

기능이나 작업을 트리거하기 위해 클릭할 수 있는 태그 또는 레이블을 표시하는 데 사용됩니다. Tag는 텍스트, 색상, 스타일 등 속성을 이용하여 사용자 정의할 수 있습니다.

TagsInput

tags = widgets.TagsInput(
    value=['pizza', 'fries'],
    allowed_tags=['pizza', 'fries', 'tomatoes', 'steak'],
    allow_duplicates=False
)
tags

TagsInput

ColorsInput

ColorsInput 위젯은 색상 목록을 선택하거나 생성할 수 있습니다. 색상을 drag&drop을 통해 순서를 변경하거나 허용되는 값을 제한하거나, 색상 중복을 방지하는데 사용합니다.

color_tags = widgets.ColorsInput(
    value=['red', '#2f6d30'],
    # allowed_tags=['red', 'blue', 'green'],
    # allow_duplicates=False
)
color_tags

ColorsInput

Float and Integer Input widgets

floatsinput = widgets.FloatsInput(
    value=[1.3, 4.56, 78.90],
    tag_style='info',
    format = '.2f'
)
floatsinput

Float

intsinput = widgets.IntsInput(
    value=[1, 4, 3243],
    min=0,
    max=1000000,
    format='$,d'
)
intsinput


Date picker

사용자가 날짜를 선택할 수 있는 widget 유형입니다.

widgets.DatePicker(
    description='Pick a Date',
    disabled=False
)


Time picker

사용자가 시간을 선택할 수 있는 widget 유형입니다.

widgets.TimePicker(
    description='Pick a Time',
    disabled=False
)


Datetime picker

사용자가 날짜와 시간을 모두 선택할 수 있는 widget 유형입니다.

widgets.DatetimePicker(
    description='Pick a Time',
    disabled=False
)


Naive picker

widgets.NaiveDatetimePicker(description='Pick a Time')

Color picker

사용자가 색상을 선택할 수 있는 widget 유형입니다.

widgets.ColorPicker(
    concise=False,
    description='Pick a color',
    value='blue',
    disabled=False
)


File Upload

widgets.FileUpload(
    accept='',  # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf'
    multiple=False  # True to accept multiple files upload else False
)

uploader = widgets.FileUpload()
display(uploader)

# upload something...

# once a file is uploaded, use the `.value` attribute to retrieve the content:
uploader.value
#=> (
#=>   {
#=>     'name': 'example.txt',
#=>     'type': 'text/plain',
#=>     'size': 36,
#=>     'last_modified': datetime.datetime(2020, 1, 9, 15, 58, 43, 321000, tzinfo=datetime.timezone.utc),
#=>     'content': <memory at 0x10c1b37c8>
#=>   },
#=> )

Container/Layout widgets

Box

items = [widgets.Label(str(i)) for i in range(4)]
widgets.Box(items)

HBox

items = [widgets.Label(str(i)) for i in range(4)]
widgets.HBox(items)

VBox

items = [widgets.Label(str(i)) for i in range(4)]
left_box = widgets.VBox([items[0], items[1]])
right_box = widgets.VBox([items[2], items[3]])
widgets.HBox([left_box, right_box])

GridBox

items = [widgets.Label(str(i)) for i in range(8)]
widgets.GridBox(items, layout=widgets.Layout(grid_template_columns="repeat(3, 100px)"))

Accordion

accordion = widgets.Accordion(children=[widgets.IntSlider(), widgets.Text()], titles=('Slider', 'Text'))
accordion

Tabs

tab_contents = ['P0', 'P1', 'P2', 'P3', 'P4']
children = [widgets.Text(description=name) for name in tab_contents]
tab = widgets.Tab()
tab.children = children
tab.titles = [str(i) for i in range(len(children))]
tab

Stack

dropdown = widgets.Dropdown(options=['button', 'slider'])
widgets.jslink((dropdown, 'index'), (stack, 'selected_index'))
widgets.VBox([dropdown, stack])

Nesting tabs and accordions

tab_nest = widgets.Tab()
tab_nest.children = [accordion, accordion]
tab_nest.titles = ('An accordion', 'Copy of the accordion')
tab_nest


List of all Available Widgets

for i, el in enumerate(dir(widgets)):
    print(str(i + 1) + '.', el)

Output:

1. Accordion
2. AppLayout
3. Audio
4. BoundedFloatText
5. BoundedIntText
6. Box
7. Button
8. ButtonStyle
9. CallbackDispatcher
10. Checkbox
11. Color
12. ColorPicker
13. ColorsInput
14. Combobox
15. Controller
16. CoreWidget
17. DOMWidget
18. DatePicker
19. Datetime
20. DatetimePicker
21. Dropdown
22. FileUpload
23. FloatLogSlider
24. FloatProgress
25. FloatRangeSlider
26. FloatSlider
27. FloatText
28. FloatsInput
29. GridBox
30. GridspecLayout
31. HBox
32. HTML
33. HTMLMath
34. Image
35. IntProgress
36. IntRangeSlider
37. IntSlider
38. IntText
39. IntsInput
40. Label
41. Layout
42. NaiveDatetimePicker
43. NumberFormat
44. Output
45. Password
46. Play
47. RadioButtons
48. Select
49. SelectMultiple
50. SelectionRangeSlider
51. SelectionSlider
52. SliderStyle
53. Stack
54. Style
55. Tab
56. TagsInput
57. Text
58. Textarea
59. TimePicker
60. ToggleButton
61. ToggleButtons
62. ToggleButtonsStyle
63. TwoByTwoLayout
64. TypedTuple
65. VBox
66. Valid
67. ValueWidget
68. Video
69. Widget
70. __builtins__
71. __cached__
72. __doc__
73. __file__
74. __jupyter_widgets_base_version__
75. __jupyter_widgets_controls_version__
76. __loader__
77. __name__
78. __package__
79. __path__
80. __protocol_version__
81. __spec__
82. __version__
83. _handle_ipython
84. _version
85. dlink
86. docutils
87. domwidget
88. fixed
89. get_ipython
90. interact
91. interact_manual
92. interaction
93. interactive
94. interactive_output
95. jsdlink
96. jslink
97. link
98. load_ipython_extension
99. os
100. register
101. register_comm_target
102. trait_types
103. valuewidget
104. widget
105. widget_bool
106. widget_box
107. widget_button
108. widget_color
109. widget_controller
110. widget_core
111. widget_date
112. widget_datetime
113. widget_description
114. widget_float
115. widget_int
116. widget_layout
117. widget_link
118. widget_media
119. widget_output
120. widget_selection
121. widget_selectioncontainer
122. widget_serialization
123. widget_string
124. widget_style
125. widget_tagsinput
126. widget_templates
127. widget_time
128. widget_upload
129. widgets
반응형