You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bokeh应用:触发回调时无法更新MultiSelect选项问题求助

Let's break down what's going wrong with your code and fix it step by step:

The Core Issue

You've tied your search/update logic to the MultiSelect component's options change event, but that's backwards. What you actually want is to trigger a search when the user types in the TextInput, then update the MultiSelect options with those results.

Corrected Code

Here's the revised version with fixes and improvements:

def createtab_search(): 
    # Define MultiSelect first so the callback can access it
    multi_select = MultiSelect(title="Results:", value=[], options=[]) 

    # Combine input tracking and search logic into one callback
    def callback_text_input(attr, old, new): 
        print(f"Previous input: {old}") 
        print(f"New input: {new}")
        
        # Run your search with the latest input value
        search_results = search_function(new)
        
        # Generate options - handle both dict and list results
        if isinstance(search_results, dict):
            options = [(key, key) for key in search_results.keys()]
        else:
            options = [(item, item) for item in search_results]
        
        # Update the MultiSelect options directly
        multi_select.options = options 

    text_input = TextInput(value="search here", title="Search:") 
    # Bind the callback to TextInput's value change event
    text_input.on_change("value", callback_text_input) 

    # Layout and tab setup
    layout = column(text_input, multi_select) 
    tab = Panel(child=layout, title='Search') 
    return tab

Key Changes Explained

  1. Callback Binding Fix
    We moved all the search and option-update logic into the TextInput's value change callback. Now every time the user types something, the search runs and the dropdown updates immediately.

  2. Scope Adjustment
    We defined multi_select before the callback function, ensuring the callback can access and modify the component without scope issues.

  3. Result Handling Robustness
    Added a check for the type of search_results (dict vs. list) to avoid errors if your search function returns different data structures. Adjust this part to match whatever your search_function actually returns.

  4. Cleaner Logic Flow
    Merged the two separate callbacks into one, making the code easier to follow and maintain.

Quick Notes

  • Make sure your search_function returns an iterable (like a list or dictionary) — if it returns something else, tweak the option-generation code to match.
  • Since you're running this via bokeh serve --show my_app, this server-side callback will work perfectly (no need for CustomJS here).

内容的提问来源于stack exchange,提问作者BenP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:50:24