Py.Cafe

kolibril13/

my-counter-widget

Customizable "Hello World" Widget using AnyWidget Library

DocsPricing
  • app.py
  • requirements.txt
  • widget.css
  • widget.js
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import anywidget
import traitlets
from pathlib import Path

class HelloWidget(anywidget.AnyWidget):
    _esm = Path("widget.js")
    _css= Path("widget.css")
    count = traitlets.Int(0).tag(sync=True)

counter = HelloWidget()
counter.count = 42
counter

page = counter
widget.css
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
.hello-widget {
	background: linear-gradient(
		90deg,
		#9933ff 20%,
		#ff6666 40%,
		#faca30 60%,
		#00cd99 80%,
		#00ccff 100%
	);
	border-radius: 10px;
	border: none;
	color: white;
	cursor: pointer;
	font-family: "Roboto", sans-serif;
	font-size: 2em;
	margin: 10px;
	padding: 10px 20px;
	transition: transform 0.25s ease-in-out;
}
.hello-widget:hover {
	transform: scale(1.05);
}
widget.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function render({ model, el }) {
    let getCount = () => model.get("count");
    let button = document.createElement("button");
    button.classList.add("hello-widget");
    button.innerHTML = `count is ${getCount()}`;

    button.addEventListener("click", () => {
        model.set("count", getCount() + 1);
        model.save_changes();
    });
    model.on("change:count", () => {
        button.innerHTML = `count is ${getCount()}`;
    });
    el.appendChild(button);
}
export default { render };