Python Bokeh:如何在子程序中更新切换按钮 - 在主程序中定义

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

我有以下简单的散景示例。开始按钮在子例程中启动不定式 while 循环,一旦按下按钮 3 或取消选中复选框,该循环应立即停止 运行ning。 Button2 检查没有循环的状态,工作正常。由于 button3 和复选框 cb 是在 main 中定义的,因此 button1 调用的子例程无法识别更改。有办法解决这个问题吗?

我使用的散景版本是 1.0.1。您可以 运行 本地示例 bokeh serve script.py 并在您的浏览器中查看 (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))

我认为 while 循环干扰了 Tornado IO_loop。我建议您改用 add_periodic_callback (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)