Skip to content

Instantly share code, notes, and snippets.

@yunwoong7
Last active December 15, 2021 11:58
Show Gist options
  • Save yunwoong7/b4eb77dd0ef09c06721e5e3b4870386a to your computer and use it in GitHub Desktop.
Save yunwoong7/b4eb77dd0ef09c06721e5e3b4870386a to your computer and use it in GitHub Desktop.
ipywidgets widget 설명 / 사용방법

ipywidgets Widget List

위젯 형식 위젯
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

IntSlider

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

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

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',
)

수직 슬라이더 예시

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',
)

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'
)

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',
)

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',
)

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'

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'

BoundedIntText

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

BoundedFloatText

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

IntText

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

FloatText

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


Boolean widgets

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)

Checkbox

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

Valid

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


Selection widgets

Dropdown

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

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

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
)

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'}
        )
    ]
)

Select

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

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
)

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
)

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
)

SelectMultiple

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


String widgets

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
)

Password

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

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

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])

Tags input widget

# 8.0 (not released yet)
# tags = widgets.TagsInput(
#     value=['pizza', 'fries'],
#     allowed_tags=['pizza', 'fries', 'tomatoes', 'steak'],
#     allow_duplicates=False
# )
# tags
# 8.0 (not released yet)
# color_tags = widgets.ColorsInput(
#     value=['red', '#2f6d30'],
#     # allowed_tags=['red', 'blue', 'green'],
#     # allow_duplicates=False
# )
# color_tags

Date picker

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

Time picker

# 8.0 (not released yet)
# widgets.TimePicker(
#     description='Pick a Time',
#     disabled=False
# )

Datetime picker

# 8.0 (not released yet)
# widgets.DatetimePicker(
#     description='Pick a Time',
#     disabled=False
# )

Color picker

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

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

Stacked

# 8.0 (not released yet)
# button = widgets.Button(description='Click here')
# slider = widgets.IntSlider()
# stacked = widgets.Stacked([button, slider])
# stacked  # will show only the button
# 8.0 (not released yet)
# dropdown = widgets.Dropdown(options=['button', 'slider'])
# widgets.jslink((dropdown, 'index'), (stacked, 'selected_index'))
# widgets.VBox([dropdown, stacked])

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)
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. Combobox
14. Controller
15. CoreWidget
16. DOMWidget
17. DatePicker
18. Datetime
19. Dropdown
20. FileUpload
21. FloatLogSlider
22. FloatProgress
23. FloatRangeSlider
24. FloatSlider
25. FloatText
26. GridBox
27. GridspecLayout
28. HBox
29. HTML
30. HTMLMath
31. Image
32. IntProgress
33. IntRangeSlider
34. IntSlider
35. IntText
36. Label
37. Layout
38. NumberFormat
39. Output
40. Password
41. Play
42. RadioButtons
43. Select
44. SelectMultiple
45. SelectionRangeSlider
46. SelectionSlider
47. SliderStyle
48. Style
49. Tab
50. Text
51. Textarea
52. ToggleButton
53. ToggleButtons
54. ToggleButtonsStyle
55. TwoByTwoLayout
56. VBox
57. Valid
58. ValueWidget
59. Video
60. Widget
61. __builtins__
62. __cached__
63. __doc__
64. __file__
65. __jupyter_widgets_base_version__
66. __jupyter_widgets_controls_version__
67. __loader__
68. __name__
69. __package__
70. __path__
71. __protocol_version__
72. __spec__
73. __version__
74. _handle_ipython
75. _version
76. dlink
77. docutils
78. domwidget
79. fixed
80. get_ipython
81. handle_kernel
82. interact
83. interact_manual
84. interaction
85. interactive
86. interactive_output
87. jsdlink
88. jslink
89. link
90. load_ipython_extension
91. os
92. register
93. register_comm_target
94. trait_types
95. util
96. valuewidget
97. version_info
98. widget
99. widget_bool
100. widget_box
101. widget_button
102. widget_color
103. widget_controller
104. widget_core
105. widget_date
106. widget_description
107. widget_float
108. widget_int
109. widget_layout
110. widget_link
111. widget_media
112. widget_output
113. widget_selection
114. widget_selectioncontainer
115. widget_serialization
116. widget_string
117. widget_style
118. widget_templates
119. widget_upload
120. widgets
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment