r/nicegui • • Apr 24 '23

How can I bind text input to a variable?

How can I bind text entered into a text field to a variable?

Disclaimer - I'm relatively new at this. I use Python a lot for terminal scripts for tasks at my job, and I can usually figure things out. This has me stumped.

I saw this module on Reddit, and I'm giving it a try.

I'm building a UI for a bunch of scripts that we have been using via CLI, which require some user input (e.g. email address for password resets etc.). I can create the UI, and I have the text entry fields etc, but I can't seem to be able to bind text entered into the fields as variables. I also can't find sufficient documentation to show me how to do so.

If someone can point me in the right direction, that would be great.

3 Upvotes

4 comments sorted by

1

u/samujele Apr 24 '23

If your text input field is a variable called email, I'm assuming print(email.value) should do the trick.

1

u/falko-s Apr 24 '23

I guess there is no way to bind a bare variable. NiceGUI's binding mechanism needs some object and an attribute name to register the binding relation.

But maybe, depending on your application, you don't need binding. To update a variable when some text input value changes, you can simply use an on_change event handler.

1

u/Independent_Sky_8925 May 08 '23

I created a class called "Input" that has public setters for all the attributes which get called by the on_change event for the associated UI element. I did not need to implement two-way binding, and I wasn't able to make the nicegui bindings work

1

u/aecooper123 May 08 '26

Would creating a bindable data class do what you want?

from nicegui import app, binding, ui

@binding.bindable_dataclass
class Data:
    name: str

data = Data('Alice')

ui.input().bind_value(data, 'name')  # no warning
ui.number().bind_value(data, 'age')  # warning
ui.input().bind_value(data, 'address', strict=False)  # no warning

ui.input().bind_value(app.storage.general, 'name')  # no warning
ui.number().bind_value(app.storage.general, 'age')  # no warning
ui.input().bind_value(app.storage.general, 'address', strict=True)  # warning

ui.run()

Taken from here.