DEV Community

Daisuke Majima
Daisuke Majima

Posted on • Originally published at qiita.com

Adding UI to Google Colab: forms, sliders, buttons and more

Adding UI to Colab

You can show UI in a Google Colaboratory notebook. Input forms, buttons, and so on are handy when other people use your notebook. A form's value is reflected into the cell's variable.

Live Colab notebook sample


Cell title

#@title cell title
Enter fullscreen mode Exit fullscreen mode

Input form

You can reflect the form's content into a variable in the cell.

variable = "the form is reflected into the variable" #@param {type:"string"}
# for a number: #@param {type:"number"}
Enter fullscreen mode Exit fullscreen mode

Select box

dropdown = 'value' #@param ["1st option", "2nd option", "3rd option"] {allow-input: true}
Enter fullscreen mode Exit fullscreen mode

Date input

date_input = '2018-03-22' #@param {type:"date"}
Enter fullscreen mode Exit fullscreen mode

Slider

number_slider = 0.1 #@param {type:"slider", min:-1, max:1, step:0.1}
Enter fullscreen mode Exit fullscreen mode

Checkbox

boolean_checkbox = True #@param {type:"boolean"}
Enter fullscreen mode Exit fullscreen mode

Markdown

#@markdown ---
#@markdown #Big
#@markdown ###Middle
#@markdown #####Little
#@markdown ---
Enter fullscreen mode Exit fullscreen mode

A button via the DOM

from IPython.display import display, Javascript
from google.colab import output
from google.colab.output import eval_js

js = Javascript('''
            async function load_image() {
                const div = document.createElement('div');
                var button = document.createElement('button');
                var log = document.createElement('div');

                button.textContent = "button";
                button.onclick = function(){
                    log.innerHTML = "Button Clicked.";
                }
                div.appendChild(button)
                div.appendChild(log)

                document.querySelector("#output-area").appendChild(div);
                return
                } ''')

display(js)
eval_js('load_image()')
Enter fullscreen mode Exit fullscreen mode


Originally published in Japanese on Qiita. I build apps with Core ML and write about machine learning. GitHub / X

Top comments (0)