如何在不使用回调函数的情况下定义带有输入框的全局变量?



我在python中使用Dash。我有一个搜索框,它接受输入值。不幸的是,我的代码的其余部分开始并需要一个全局变量,这是输入文本框的结果。由于输入框具有回调函数,因此我需要定义一个全局变量,一旦在输入框中插入新值,该变量就会更改。这种情况永远不会发生,因为代码从变量开始,当我在输入框中插入新值时,它永远不会改变值。如何在不使用回调函数的情况下定义带有输入框的变量?我需要一些东西作为input()在python中,但与输入文本框。

search_bar = dbc.Row([
html.Div(id="output_ricerca2"),
dbc.Input(id="input", placeholder="Stock...", type="text")
])    
value='test' #i would here the value of input box as variable
other code using this value
page_1_layout = html.Div([
html.Br(),
html.H1('Page 1')
#I need here the update value of the input box
])
@app.callback(Output('output_ricerca2', 'children'),
[Input('output_ricerca', 'n_clicks')],
#[Input('btn-submit', 'n_clicks')],
[State('url', 'pathname')])
def update_output(clicks, pathname):
if clicks is not None:
result_titolo=pathname.split("/"),
print('path:'),
print(result_titolo)
return (result_titolo)

@app.callback(dash.dependencies.Output('page-content2', 'children'),
[dash.dependencies.Input('url', 'pathname')])
def display_page(pathname):
if pathname == '/Overview':
return page_1_layout
elif pathname == '/PricePerformance':
return page_2_layout
elif pathname == '/BalanceSheet':
return page_3_layout
elif pathname == '/Graphs':
return page_4_layout
elif pathname == '/Competitors':
return page_5_layout
else:
return ''

@app.callback(Output("output_ricerca", "children"), [Input("input", "value")])
def update_output(value):
apiurl = "https://query1.finance.yahoo.com/v1/finance/search?q="+value
r = requests.get(apiurl)
data = r.json()
if data['quotes']:
exchange = data["quotes"][0]['exchange']
print(exchange)
table_rows = [html.Tr([dcc.Link(href=z.get('symbol'),children=[z.get('symbol')]),html.Td(z.get('longname')),html.Td(z.get('quoteType')+'-'+z.get('exchange'))]) for z in data['quotes']]
#rows_longname = [html.Tr([html.Td(z.get('longname'))]) for z in data['quotes']]
output_table = html.Div(
html.Table([ 
html.Th(scope="row",
children=[
html.Td('Symbols'),
])
]+table_rows), 
style={})
return output_table

不幸的是,我的其余代码开始并需要一个全局变量,该变量是输入文本框

的结果

我认为这就是问题所在。尝试使用一个全局变量,就像你描述的那样,与React/Dash和回调结构相反。

如果您的代码的其余部分从该值运行,然后设置回调,以便它将raise dash.exceptions.PreventUpdate,如果输入仍然具有默认值。下面是一个例子:

@app.callback(Output("output_ricerca", "children"), [Input("input", "value")])
def update_output(value):
if not value:
raise dash.exceptions.PreventUpdate
# the rest of your code...

或者,如果您为该组件设置了默认值,例如value='foo',那么您的条件可能是if value == 'foo'

问题是当你这样做的时候:

search_bar = dbc.Row([
html.Div(id="output_ricerca2"),
dbc.Input(id="input", placeholder="Stock...", type="text")
])    
value='test'

变量值因输入框的值不同而不同。我需要它们是相同的变量。我需要将输入框的值定义为global。对所有代码有效,可通过输入框更改。

最新更新