Gradio provides several event listener functions that can be used to attach multiple events to a single function.
gr.on(
triggers,
fn,
inputs=None,
outputs=None,
api_visibility="public",
api_name=None,
api_description=None,
scroll_to_output=False,
show_progress="full",
queue=True,
batch=False,
max_batch_size=4,
preprocess=True,
postprocess=True,
cancels=None,
trigger_mode=None,
js=None,
concurrency_limit="default",
concurrency_id=None,
validator=None
)
Sets up an event listener that triggers a function when the specified event(s) occur. This is especially useful when the same function should be triggered by multiple events. Only a single API endpoint is generated for all events in the triggers list.
Parameters
triggers
Sequence[EventListenerCallable] | EventListenerCallable | None
default:"None"
List of triggers to listen to, e.g. [btn.click, number.change]. If None, will run on app load and changes to any inputs.
fn
Callable | None
default:"None"
The function to call when this event is triggered.
inputs
Component | Sequence[Component] | None
default:"None"
List of gradio components to use as inputs.
outputs
Component | Sequence[Component] | None
default:"None"
List of gradio components to use as outputs.
Example
import gradio as gr
with gr.Blocks() as demo:
with gr.Row():
input = gr.Textbox()
button = gr.Button("Submit")
output = gr.Textbox()
gr.on(
triggers=[button.click, input.submit],
fn=lambda x: x,
inputs=[input],
outputs=[output]
)
demo.launch()
api
gr.api(
fn,
api_name=None,
api_description=None,
queue=True,
batch=False,
max_batch_size=4,
concurrency_limit="default",
concurrency_id=None,
api_visibility="public"
)
Sets up an API or MCP endpoint for a generic function without needing to define event listeners or components. Derives its typing from type hints in the provided function’s signature rather than the components.
Parameters
The function to call when this event is triggered. The function should be fully typed, and the type hints will be used to derive the typing information for the API/MCP endpoint.
Defines how the endpoint appears in the API docs.
Description of the API endpoint.
If True, will place the request on the queue.
If True, then the function should process a batch of inputs.
Maximum number of inputs to batch together.
concurrency_limit
int | None | Literal['default']
default:"'default'"
If set, this is the maximum number of this event that can be running simultaneously.
If set, this is the id of the concurrency group.
api_visibility
Literal['public', 'private', 'undocumented']
default:"'public'"
Controls the visibility and accessibility of this endpoint.
Example
import gradio as gr
with gr.Blocks() as demo:
def add_and_slice(a: int, b: int, c: list[str]) -> tuple[int, str]:
return a + b, c[a:b]
gr.api(add_and_slice, api_name="add_and_slice")
demo.launch()