How to update the gr.Dropdown() choices from a Database

Hi, I want to use the gr.Dropdown() of gradio for my project.

My idea is when a user clicks the update_btn, the gr.Dropdown() choices will be updated. The type of both initial and updated chioces are <class ‘list’>, formatted as follows:: ['0,Cat', '1,Dog', '2,Duck', '3,Bird']. The updated choices come from the List_from_db() function that would connect to my database based on MySQL to get a list. I confirmed that my database function is working.

But it doesn’t work when I run my program. The gr.Dropdown() doesn’t display any selectable options when I move the cursor over the dropdown element.

My gradio version is 4.7.1 and I also referred to the How to update the gr.Dropdown() block in Gradio Blocks and tried to implement it based on his logic, but the result didn’t work. The problem is very similar to mine, but the difference is that I want to update the gr.Dropdown choices, and the source of the updated choices are the list data returned by my database.

Here is part of my code, any guidance would be appreciated!

(The actual function is more complicated. The following code is simple logic of my function. The List_from_db() is about the database function, but I don’t provide any code here because if I included, it would make my article too long.)

def List_from_db():
    # -------------------------------------------------------------------------------------
    # Create Database connection
    # Get a List from Database
    # The type of returned value updated_list is <class 'list'>, and the format is just like: ['0,Cat', '1,Dog', '2,Duck', '3,Bird']
    # -------------------------------------------------------------------------------------
    return updated_list


def updatedList_from_db():
    list_info = List_from_db()
    return gr.Dropdown(choices=list_info)

# gradio version = 4.7.1

with gr.Blocks() as app:
    with gr.Row():
        dropdown_info = gr.Dropdown(choices=List_from_db(), label="Dropdown")
        with gr.Row():
            update_btn = gr.Button("Update Dropdown")

    update_btn.click(updatedList_from_db, inputs=[], outputs=dropdown_info)

app.launch(share=True)
1 Like