Python Bokeh: How to update a Toggle button - defined in the main - in a subroutine

佐手、 提交于 2019-12-11 06:49:05

问题


I have the following simple bokeh example. The start button starts an infinitive while loop in a subroutine, which should stop running as soon as button 3 is pressed or the checkbox is unchecked. Button2 checks the status without the loop which works fine. As button3 and the checkbox cb are defined in the main the subroutine called by button1 does not recognize the change. Is there a way to solve this?

I used bokeh version 1.0.1. You can run the example lokally with bokeh serve script.py and view it in your browser (http://localhost:5006).

from bokeh.models import Column
from bokeh.plotting import curdoc
from bokeh.models.widgets import Button, Toggle, CheckboxGroup
import time

def start_loop():
    while (not button3.active) and (len(cb.active)):
        time.sleep(1)
        print(button3.active)
        print(cb.active)

def check_status():
    print(button3.active)
    print(cb.active)

button1 = Button(label = "start")
button1.on_click(start_loop)

button2 = Button(label = "check status")
button2.on_click(check_status)

button3 = Toggle(label="stop")
cb = CheckboxGroup(labels=['stop'],active=[0])

curdoc().add_root(Column(button1,button2,button3,cb))


回答1:


I think the while loop interferes the Tornado IO_loop. I advice you to use add_periodic_callback instead (Bokeh v1.1.0)

from bokeh.models import Column
from bokeh.plotting import curdoc
from bokeh.models.widgets import Button, Toggle, CheckboxGroup
import time

# def start_loop():
#     while (not button3.active) and (len(cb.active)):
#         time.sleep(1)
#         print(button3.active)
#         print(cb.active)

def check_status():
    print(button3.active)
    print(cb.active)

# button1 = Button(label = "start")
# button1.on_click(start_loop)

button2 = Button(label = "check status")
button2.on_click(check_status)

button3 = Toggle(label = "stop")
cb = CheckboxGroup(labels = ['stop'], active = [0])

curdoc().add_root(Column(button2, button3, cb))
curdoc().add_periodic_callback(check_status, 1000)


来源:https://stackoverflow.com/questions/55971688/python-bokeh-how-to-update-a-toggle-button-defined-in-the-main-in-a-subrout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!