Ошибка типа:> не поддерживается между экземплярами NoneType и int - PullRequest
0 голосов
/ 18 февраля 2020

Я пытаюсь отключить кнопку при нажатии, пока процесс не завершится, а затем включить ее снова. Вот схема шагов:

  1. пользователь нажимает кнопку
  2. кнопка отключается
  3. скрипт запускается
  4. скрипт заканчивается запуск
  5. кнопка включена
  6. другой элемент обновляется с выводом скрипта

или я просто выполняю dcc.loading в этом случае.

Вот мой код:

import dash
import dash_html_components as html
from dash.dependencies import Input, Output
from Missing_relation_All import my_DB_func


external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    html.Button('Create Missing Relation Script', id='button', disabled=False),
    # other element
    html.Div(id='other-element'),
    # trigger div
    html.Div(id='trigger', children=0, style=dict(display='none'))
])


@app.callback(
    Output('button', 'disabled'),
    [Input('button', 'n_clicks'),
     Input('trigger', 'children')])
def trigger_function(n_clicks, trigger):
    context = dash.callback_context.triggered[0]['prop_id'].split('.')[0]
    context_value = dash.callback_context.triggered[0]['value']

    # if the button triggered the function
    if context == 'button':
        # if the function is triggered at app load, this will not disable the button
        # but if the function is triggered by clicking the button, this disables the button as expected
        if n_clicks > 0:
            return True
        else:
            return False
    # if the element function completed and triggered the function
    else:
        # if the function is triggered at app load, this will not disable the button
        # but if the function is triggered by the function finishing, this enables the button as expected
        return False


@app.callback(
    [Output('other-element', 'children'),
     Output('trigger', 'children')],
    [Input('button', 'n_clicks')])
def update_element(n_clicks):
    my_DB_func()
    return (
        'my element value',
        1  # update the trigger value
    )



if __name__ == '__main__':
    app.run_server(debug=True)

Поэтому, когда я пытаюсь запустить приложение, я получаю эту ошибку:

TypeError: '>' not supported between instances of 'NoneType' and 'int'

File "C:\Users\haroo501\PycharmProjects\My_Check_Missing_Relation_Tool\newbuttontest.py", line 32, in trigger_function
if n_clicks > 0:
TypeError: '>' not supported between instances of 'NoneType' and 'int'

Traceback (most recent call last):
  File "C:\Users\haroo501\PycharmProjects\My_Check_Missing_Relation_Tool\newbuttontest.py", line 32, in trigger_function
    if n_clicks > 0:
TypeError: '>' not supported between instances of 'NoneType' and 'int'

Так что мне нужно сделать после нажатия кнопки, чтобы она зависла или отключилась до:

Process finished with exit code -1

после завершения sh процесса или завершения sh сценария, основанного на def?

1 Ответ

0 голосов
/ 18 февраля 2020

Я решил это следующим образом, когда изменил эту часть:

        if n_clicks > 0:
            return True
        else:
            return False

на эту:

        if n_clicks is None:
            raise dash.exceptions.PreventUpdate
        else:
            return True

и эту часть:

@app.callback(
    [Output('other-element', 'children'),
     Output('trigger', 'children')],
    [Input('button', 'n_clicks')])
def update_element(n_clicks):
    my_DB_func()
    return (
        'my element value',
        1  # update the trigger value
    )

на эту :

def update_element(n_clicks):
    if n_clicks == True:
        my_DB_func()
    return (
        'my element value',
        1 # update the trigger value
    )

, так как конечный код будет выглядеть примерно так:

import dash
import dash_html_components as html
from dash.dependencies import Input, Output
from Missing_relation_All import my_DB_func
from dash.exceptions import PreventUpdate

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    html.Button('Create Missing Relation Script', id='button', disabled=False),
    # other element
    html.Div(id='other-element'),
    # trigger div
    html.Div(id='trigger', children=0, style=dict(display='none'))
])


@app.callback(
    Output('button', 'disabled'),
    [Input('button', 'n_clicks'),
     Input('trigger', 'children')])
def trigger_function(n_clicks, trigger):
    context = dash.callback_context.triggered[0]['prop_id'].split('.')[0]
    context_value = dash.callback_context.triggered[0]['value']

    # if the button triggered the function
    if context == 'button':
        # if the function is triggered at app load, this will not disable the button
        # but if the function is triggered by clicking the button, this disables the button as expected
        if n_clicks is None:
            raise dash.exceptions.PreventUpdate
        else:
            return True
    # if the element function completed and triggered the function
    else:
        # if the function is triggered at app load, this will not disable the button
        # but if the function is triggered by the function finishing, this enables the button as expected
        return False


@app.callback(
    [Output('other-element','children'),
     Output('trigger','children')],
    [Input('button','n_clicks')])
def update_element(n_clicks):
    if n_clicks == True:
        my_DB_func()
    return (
        'my element value',
        1 # update the trigger value
    )


if __name__ == '__main__':
    app.run_server(debug=True)

...