How to await for a UI click (for a linear flow)? #290
-
Within an async def func():
clicked = False
def onclick():
clicked = True
with ui.column():
ui.button('Click me', on_click=functools.partial(onclick))
ui.label('Click the button')
await # ??? TODO wait for button click or clicked == True
ui.label('The button was clicked')
ui.timer(interval=1, callback=functools.partial(func), once=True)
ui.run() I am trying to mimic the simple linear flow of short console scripts that prompts for And then how could we gracefully terminate the script and prevent the resulting HTML page from trying to reconnect? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Looks like Here is a minimum example: async def flow():
clicked = asyncio.Event()
ui.button('Click me', on_click=clicked.set)
await clicked.wait()
ui.notify('You clicked me!')
ui.button('Start flow', on_click=flow) Regarding the graceful shutdown: Could you, please, open a new discussion with a bit more detail about what you are trying to do? Then it is easier for others to find and we have dedicated space to discuss possible implementations. |
Beta Was this translation helpful? Give feedback.
-
For future reference, I rewrote my example with asyncio.Event: import asyncio
from nicegui import ui, app
async def wait_for_click(element):
continue_event = asyncio.Event()
element.on('click', continue_event.set)
await continue_event.wait()
async def flow():
with ui.column():
sli = ui.slider(min=1, max=10, value=1)
ui.input('Delay (s)').bind_value(sli, 'value')
btn = ui.button('Click')
ui.label('Click the button')
await wait_for_click(btn)
ui.label(f'The button was clicked. Sleeping for {sli.value} seconds')
await asyncio.sleep(sli.value)
ui.label('End of flow')
btn = ui.button('Shutdown')
await wait_for_click(btn)
app.shutdown()
#app.on_startup(flow) # Is this supposed to work?
ui.timer(interval=1, callback=flow, once=True) # I have to use the timer instead
ui.run(reload=False) Which gives nice one-line waiting statements. We can see that the slider events are processed while waiting. |
Beta Was this translation helpful? Give feedback.
Looks like
asyncio.Event
is your friend: https://stackoverflow.com/a/44892240/3419103Here is a minimum example:
Regarding the graceful shutdown: Could you, please, open a new discussion with a bit more detail about what you are trying to do? Then it is easier for others to find and we have dedicated space to discuss possible implementations.