Get help from the marimo community

Updated 4 months ago

How to use a set_value function when using anywidget?

In JupyterLab I can use a simple CounterWidget with anywidget like this.
Plain Text
import anywidget
import traitlets


class CounterWidget(anywidget.AnyWidget):
    _esm = """
    function render({ model, el }) {
      let count = () => model.get("value");
      let btn = document.createElement("button");
      btn.innerHTML = `count is ${count()}`;
      btn.addEventListener("click", () => {
        model.set("value", count() + 1);
        model.save_changes();
      });
      model.on("change:value", () => {
        btn.innerHTML = `count is ${count()}`;
      });
      el.appendChild(btn);
    }
    export default { render };
    """

    value = traitlets.Int(40).tag(sync=True)

    def set_value(self, new_value):
        """Set the value of the counter programmatically."""
        self.value = new_value

widget  = CounterWidget()
widget

Plain Text
widget.set_value(100)

and this works (screenshot 1).
When I try to do the same within a marimo notebook, then widget.set_value(100) fails.
Any idea how I can overcome this? Suggestions are very welcome!
Here's the marimo script:
Plain Text
import anywidget
import traitlets
import marimo as mo


class CounterWidget(anywidget.AnyWidget):
    _esm = """
    function render({ model, el }) {
      let count = () => model.get("value");
      let btn = document.createElement("button");
      btn.innerHTML = `count is ${count()}`;
      btn.addEventListener("click", () => {
        model.set("value", count() + 1);
        model.save_changes();
      });
      model.on("change:value", () => {
        btn.innerHTML = `count is ${count()}`;
      });
      el.appendChild(btn);
    }
    export default { render };
    """

    value = traitlets.Int(40).tag(sync=True)

    def set_value(self, new_value):
        """Set the value of the counter programmatically."""
        self.value = new_value

widget = mo.ui.anywidget(CounterWidget())

widget
Attachments
image.png
image.png
J
1 comment
Might be related to this error, when I try to set widget.value = 50
Attachment
image.png
Add a reply
Sign up and join the conversation on Discord