Skip to content

Instantly share code, notes, and snippets.

@korakot
Last active December 2, 2022 07:00
Show Gist options
  • Save korakot/c1dd8575ea9de6c218011d7bf996ba0f to your computer and use it in GitHub Desktop.
Save korakot/c1dd8575ea9de6c218011d7bf996ba0f to your computer and use it in GitHub Desktop.
Custom Colab widget example: Checkbox, ColorPicker, and Slider
from ctypes import cast, py_object
from google.colab import output
def set_var(v_id, value):
obj = cast(v_id, py_object).value
obj.value = value
output.register_callback('set_var', set_var)
class Checkbox:
def __init__(self, value=False):
self.value = value
def _repr_html_(self):
checked = 'checked' if self.value else ""
return """
<input type='checkbox' %s
onchange="
google.colab.kernel.invokeFunction(
'set_var', [ %d, this.checked ],
{})
"
>
""" % (checked, id(self))
class ColorPicker:
def __init__(self, value='#000000'):
self.value = value
def _repr_html_(self):
return """
<input type='color' value='%s'
onchange="
google.colab.kernel.invokeFunction(
'set_var', [ %d, this.value ],
{})
"
>
""" % (self.value, id(self))
class Slider:
def __init__(self, value=0, min=0, max=100, step=1):
self.value = value
self.min = min
self.max = max
self.step = step
def _repr_html_(self):
name = id(self)
return f"""
<input type="range" id="in{name}"
min="{self.min}" max="{self.max}" step="{self.step}"
value="{self.value}"
oninput="out{name}.value=in{name}.value"
onchange="
google.colab.kernel.invokeFunction(
'set_var', [{name}, this.valueAsNumber],
{{}})
"
>
<output id="out{name}">{self.value}</output>
"""
@korakot
Copy link
Author

korakot commented Oct 5, 2018

กรณี slider ก็เหมือนกัน

sl = Slider(50,0,100)
sl

เราเลื่อนเพื่อเปลี่ยน value แล้ว ผลจาก JavaScript จะส่งไปที่ python

print(sl.value)  

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment