Python中WebView+Tkinter无法访问本地Dash仪表盘的问题
解决方案
问题根源
- Dash默认监听8050端口,你当前WebView访问的
http://127.0.0.1/指向80端口,自然连接失败 - Dash的
run_server()是阻塞式调用,直接放在主线程会导致WebView无法启动;反过来先启动WebView,Dash服务还未初始化完成,同样会触发连接拒绝错误
简便解决步骤
用多线程让Dash服务在后台运行,同时指定正确的访问端口:
import threading import webview import pandas as pd import plotly.express as px from dash import Dash, html, dcc, Input, Output # 初始化Dash应用 app = Dash(__name__) # 数据处理 df = pd.read_csv("https://raw.githubusercontent.com/Coding-with-Adam/Dash-by-Plotly/master/Other/Dash_Introduction/intro_bees.csv") df = df.groupby(['State', 'ANSI', 'Affected by', 'Year', 'state_code'])[['Pct of Colonies Impacted']].mean() df.reset_index(inplace=True) # App布局 app.layout = html.Div([ html.H1("Web Application Dashboards with Dash", style={'text-align': 'center'}), dcc.Dropdown(id="slct_year", options=[ {"label": "2015", "value": 2015}, {"label": "2016", "value": 2016}, {"label": "2017", "value": 2017}, {"label": "2018", "value": 2018}], multi=False, value=2015, style={'width': "40%"} ), html.Div(id='output_container', children=[]), html.Br(), dcc.Graph(id='my_bee_map', figure={}) ]) # 回调函数 @app.callback( [Output(component_id='output_container', component_property='children'), Output(component_id='my_bee_map', component_property='figure')], [Input(component_id='slct_year', component_property='value')] ) def update_graph(option_slctd): container = "The year chosen by user was: {}".format(option_slctd) dff = df.copy() dff = dff[dff["Year"] == option_slctd] dff = dff[dff["Affected by"] == "Varroa_mites"] fig = px.choropleth( data_frame=dff, locationmode='USA-states', locations='state_code', scope="usa", color='Pct of Colonies Impacted', hover_data=['State', 'Pct of Colonies Impacted'], color_continuous_scale=px.colors.sequential.YlOrRd, labels={'Pct of Colonies Impacted': '% of Bee Colonies'}, template='plotly_dark' ) return container, fig # 定义Dash后台启动函数 def run_dash(): app.run_server(debug=False, use_reloader=False) # 关闭自动重载,避免多线程冲突 # 启动Dash服务在后台线程 dash_thread = threading.Thread(target=run_dash) dash_thread.daemon = True # 设置为守护线程,关闭主程序时自动终止 dash_thread.start() # 启动WebView加载正确的Dash地址 webview.create_window('Dash Dashboard', 'http://127.0.0.1:8050/') webview.start()
关键说明
use_reloader=False:Dash的自动重载会启动额外进程,引发多线程冲突,必须关闭- 守护线程:确保关闭WebView窗口时,Dash服务会自动终止,避免残留进程
- 端口指定:明确访问8050端口,与Dash默认监听端口保持一致
内容的提问来源于stack exchange,提问作者agussm
相关产品推荐
相关产品推荐

