You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python嵌套函数传参问题:Plotly FigureWidget参数传递异常

解决方案

1. 修正独立文件 click_events.py 的函数实现

把两个函数的硬编码f替换为传入的figure_widget参数,并确保update_x调用update_y_with_x时传递该参数:

# click_events.py
def update_y_with_x(chosen_tissue, figure_widget):
    for i, trace in enumerate(figure_widget.data):
        if trace.type == "scatter":
            # 重置所有线条宽度
            figure_widget.data[i].line.width = 1
            if chosen_tissue in trace.text:
                figure_widget.data[i].line.width = 10  # 简化1+9为10

def update_x(trace, points, selector, figure_widget):
    if len(points.point_inds) == 0:
        return
    # 移除现有条形阴影和关联线条高亮
    figure_widget.layout.shapes = ()
    for i, trace in enumerate(figure_widget.data):
        if trace.type == "scatter" and figure_widget.data[i].line.width != 1:
            figure_widget.data[i].line.width = 1
    # 获取组织标识
    chosen_tissue = figure_widget.data[points.trace_index].y[points.point_inds[0]]
    # 获取选中组织的索引
    possible_trace_indices = [i for i, trace in enumerate(figure_widget.data) if trace.type == "bar"]
    chosen_tissue_ranks = [list(figure_widget.data[index].y).index(chosen_tissue) for index in possible_trace_indices]
    for i, _ in enumerate(possible_trace_indices):
        y0 = chosen_tissue_ranks[i] + 0.5
        y1 = y0 - 1
        figure_widget.add_hrect(y0=y0,y1=y1,line_width=0,fillcolor="grey",opacity=0.3,row=1,col=i * 2 + 1)
    # 调用update_y_with_x时传递figure_widget
    update_y_with_x(chosen_tissue, figure_widget)

2. 在 main.ipynb 中正确绑定点击事件

由于Plotly的on_click回调默认仅传递trace、points、selector三个参数,需要用lambda或functools.partial把figure_widget(即你的f)绑定到回调函数中:

方法一:使用lambda

from click_events import update_x
import plotly.graph_objects as go

# 假设你的figure_widget已经创建好
f = go.FigureWidget(fig)

for i, trace in enumerate(f.data):
    if trace.type == 'bar':
        # 用lambda捕获f,传递给update_x的第四个参数
        f.data[i].on_click(lambda trace, points, selector, fig=f: update_x(trace, points, selector, fig))

方法二:使用functools.partial(更清晰)

from click_events import update_x
from functools import partial
import plotly.graph_objects as go

f = go.FigureWidget(fig)

# 预先绑定figure_widget参数
bound_update_x = partial(update_x, figure_widget=f)

for i, trace in enumerate(f.data):
    if trace.type == 'bar':
        f.data[i].on_click(bound_update_x)

问题原因说明

你之前的失败主要有两个点:

  • update_x调用update_y_with_x时没有传递figure_widget参数,导致update_y_with_x找不到对应的变量
  • Plotly的点击回调不会自动传递额外参数,必须手动通过lambda或partial把f绑定到回调函数中

内容的提问来源于stack exchange,提问作者KLM117

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 19:45:10