NiceGUI: Bind visibility to arbitrary value
All notes in this series:
- (1) NiceGUI: Always show main scrollbar
- (2) NiceGUI: Show a confirmation popup
- (3) NiceGUI: File upload and download
- (4) FastAPI: Pretty print JSON
- (5) NiceGUI with Click, Poetry, auto-reload and classes
- (6) NiceGUI: tkinter error when updating pyplot
- (7) NiceGUI: Bind visibility to arbitrary value
- (8) NiceGUI: Change threshold for binding propagation warning
- (9) NiceGUI with async classes
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.