2016-08-23 71 views
1

鏈接中的0.12.1的正式文檔給出下面的代碼來創建下拉菜單。如何在散景python中捕獲下拉小部件的值?

http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/widgets.html#userguide-interaction-widgets

但它並沒有明確提及如何捕捉下拉列表控件的值,當有人點擊並選擇從下拉菜單中的值。

from bokeh.io import output_file, show 
from bokeh.layouts import widgetbox 
from bokeh.models.widgets import Dropdown 

output_file("dropdown.html") 

menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")] 
dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu) 

show(widgetbox(dropdown)) 

問題

是看到有2種方法被稱爲on_click()& on_change(),但是從文檔無法弄清楚如何捕捉值。 我們如何將選定的值分配給新的變量?

EDIT

基於輸入從@Ascurion我已經更新我的代碼如下所示。但是,當我在下拉列表中選擇一個值時,在Spyder中的ipython控制檯中不會顯示任何內容。 請指教。

from bokeh.io import output_file, show 
    from bokeh.layouts import widgetbox 
    from bokeh.models.widgets import Dropdown 

    output_file("dropdown.html") 


    menu = [("Item 1", "item_1"), ("Item 2", "item_2"), None, ("Item 3", "item_3")] 
    dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu) 

    def function_to_call(attr, old, new): 
     print dropdown.value 

    dropdown.on_change('value', function_to_call) 
    dropdown.on_click(function_to_call) 
    show(widgetbox(dropdown)) 

回答

2

如果你設置on_change例如如下:

dropdown.on_change('value', function_to_call) 

一個可以在function_to_call訪問選定項目的值,如下所示:

def function_to_call(attr, old, new): 
    print dropdown.value 

對於這個工作下拉具有function_to_call之前被定義。

關於如何訪問與on_click和on_change(背景虛化版本12.1)小部件設置的值的文檔可以在這裏找到在頁面的頂部:

http://bokeh.pydata.org/en/latest/docs/user_guide/interaction/widgets.html

編輯

要獲得交互式反饋,您必須在服務器模式下運行散景,以便在與窗口小部件交互時評估Python代碼。我稍微改變了你的例子,允許使用

bokeh serve --show file_name.py 

命令運行。下面的代碼將打印出終端中的選定項目。

from bokeh.io import output_file, show 
from bokeh.layouts import widgetbox 
from bokeh.models.widgets import Dropdown 
from bokeh.plotting import curdoc 

menu = [("Quaterly", "time_windows"), ("Half Yearly", "time_windows"), None, ("Yearly", "time_windows")] 
dropdown = Dropdown(label="Time Period", button_type="warning", menu=menu) 

def function_to_call(attr, old, new): 
    print dropdown.value 

dropdown.on_change('value', function_to_call) 

curdoc().add_root(dropdown) 

在這裏看到更多的信息:

http://bokeh.pydata.org/en/latest/docs/user_guide/server.html

+0

感謝。我收到下面的錯誤。 dropdown.on_change('value',function_to_call(attr,old,new)) NameError:name'attr'未定義 –

+0

當調用function_to_call()時,應傳遞attr,old,new的值?請解釋這些屬性的含義。 –

+0

我應該在問題中提到的代碼之後加上你提到的代碼吧? –

相關問題