Sam Hooke

NiceGUI: Bind visibility to arbitrary value

NiceGUI gives lots of examples of using bind_visibility_from to show/hide an element based upon the value of some attribute.

For example:

from nicegui import ui

v = ui.checkbox("visible", value=True)
with ui.column().bind_visibility_from(v, "value"):
    ui.label("Only visible when checkbox is ticked")

However, they all assuume you only want visibility when the value is True. What if you want it when the value is False, or some other arbitrary value?

For that you use the backward keyword argument, which specifies a function that takes the value of the attribute, and should return a truthy value.

Visible when False §

To invert the above example so that the label is only visible when the checkbox is not ticked:

from nicegui import ui

v = ui.checkbox("visible", value=True)
with ui.column().bind_visibility_from(v, "value", backward=lambda v: not v):
    ui.label("Only visible when checkbox is *NOT* ticked")

Visible upon arbitrary value §

Or to use an arbitrary value:

from nicegui import ui

obj = ui.input(label="Write foo in here")

with ui.card().bind_visibility_from(
    obj,
    "value",
    backward=lambda v: v == "foo",
):
    ui.label("Only visible when obj.field == 'foo'")

There are some examples of this in the NiceGUI code base.