Last active
December 2, 2022 07:00
-
-
Save korakot/c1dd8575ea9de6c218011d7bf996ba0f to your computer and use it in GitHub Desktop.
Custom Colab widget example: Checkbox, ColorPicker, and Slider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
กรณี slider ก็เหมือนกัน
เราเลื่อนเพื่อเปลี่ยน value แล้ว ผลจาก JavaScript จะส่งไปที่ python