python bokeh: взаимодействие теряется при добавлении / изменении дочерних элементов в защищенной паролем информационной панели. - PullRequest
0 голосов
/ 25 апреля 2018

Я хочу добавить функцию паролей на панель управления bokeh (модифицированный и расширенный код, основанный на показанном примере здесь . Логика заключается в том, что я создаю панель управления с элементом «passblock», где можно ввести пароль и второй пустой блок. Если пароль правильный, элемент «passblock» удаляется, а пустой блок-заполнитель заполняется блоком интерактивной панели. В этом примере интерактивная панель управления является ползунком, и если вы измените его, значение будет напечатано с помощью функции обратного вызова. Хотя обратный вызов работает нормально, если я непосредственно включаю ползунок диапазона в разделе панели инструментов (см. Раздел с комментариями), он больше не работает, если пароль и пользователь были введены правильно. Даже если я добавлю range_slider и только заменим его новым в разделе verify_pwd, он не работает. Любые идеи приветствуются.

from bokeh.models.widgets import PasswordInput,Button, TextInput,PreText,RangeSlider
from bokeh.layouts import column, row

PASSWD = "1" #password
USER   = "1" #username
max_count_tries = 5 #max allowed tries before dashboard is killed
count_tries = 0  # counter for max tries

def verify_pwd():
    """ verifies if user and pwd are entered correctly. If so the password block is set to zero and the
    dashboard block which was zero before is replaced by the slider"""
    global count_tries
    global range_slider
    if (pwd.value==PASSWD) & (user.value == USER): #pwe and user entered correctly
        print('logged in')
        range_slider = RangeSlider(start=0., end=10., value=(2.,3.), step=.1, title="secret slider")
        layout.children[0] = row([])
        layout.children[1] = row([range_slider])
    else: #pwd or user are wrong
        if (pwd.value!=PASSWD) & (user.value == USER):
            mytext.text = ''.join(['wrong password!\n',str(max_count_tries-count_tries), ' tries left'])
        elif (pwd.value==PASSWD) & (user.value != USER):
            mytext.text = ''.join(['wrong user!\n',str(max_count_tries-count_tries), ' tries left'])
        else:
            mytext.text = ''.join(['wrong user and wrong password!\n',str(max_count_tries-count_tries), ' tries left'])
        count_tries += 1
        if count_tries>max_count_tries:
           layout.children[0] = row([])

def callback(attrname, old, new):
    # Get the current slider values and print the value in the console
    global range_slider
    lower = range_slider.value[0]    
    upper = range_slider.value[1]   
    print(lower,upper)

mytext = PreText() #placeholder for error message
user = TextInput(title="UserName:") # unser name entry field
pwd  = PasswordInput(title="Password:") #password entry field
btn  = Button(label="login") # button to log in 
btn.on_click(verify_pwd) # if button was clicked compare pwd and user with entries
#pwd.callback(verify_pwd)

passblock = row([user, pwd, btn, mytext]) # create a block to the dashboard where the pwd and user can be entered

range_slider = RangeSlider(start=0., end=10., value=(0.,0.), step=.1, title="dummy") # create a dummy slider which is not used
range_slider.on_change('value', callback) # callback for slider if values change

layout = column(passblock,row([])) # create a layout with the password block and an empty block which is filled as soon as the pwd and user are ok
#layout = column(passblock,range_slider)

# create bokeh document and deploy it
from bokeh.io import curdoc
curdoc().add_root(layout)

1 Ответ

0 голосов
/ 02 мая 2018

Поработав некоторое время, я нашел решение.В приведенном выше коде я забыл добавить строку «on_change» в подпрограмму verify_pwd.Добавление

range_slider.on_change('value', callback) 

после добавления нового ползунка в строке:

range_slider = RangeSlider(start=0., end=10., value=(2.,3.), step=.1, title="secret slider")

решило проблему

в качестве альтернативы также работает в версии, описанной в вопросе, если

layout.children[0] = row([])
layout.children[1] = row([range_slider])

заменяется на

layout.children[0] = row([range_slider])
...