简体   繁体   中英

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

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))

在此处输入图片说明

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM