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

FPDF2绘制表格触发TypeError:__init__()收到意外参数'cell_fill_logic'

Python FPDF绘制表格报错处理

问题描述

运行以下代码时出现错误:TypeError: __init__() got an unexpected keyword argument 'cell_fill_logic'

with pdf.table(
    borders_layout="NO_HORIZONTAL_LINES",
    cell_fill_color=(224, 235, 255),
    cell_fill_logic=lambda i, j: i % 2,
    col_widths=(42, 39, 35, 42),
    headings_style=headings_style,
    line_height=6,
    text_align=("LEFT", "CENTER", "RIGHT", "RIGHT"),
    width=160,
) as table:
    for data_row in data:
        row = table.row()

错误原因

cell_fill_logic是FPDF后续版本新增的参数,你当前使用的FPDF版本不支持该特性,导致参数识别失败。

解决方案

方案1:升级FPDF到最新版本

执行以下命令升级库:

pip install --upgrade fpdf2

升级后即可正常使用cell_fill_logic参数实现隔行变色。

方案2:手动实现隔行变色(不升级版本)

如果无法升级,可通过行索引手动控制填充颜色,示例代码如下:

with pdf.table(
    borders_layout="NO_HORIZONTAL_LINES",
    col_widths=(42, 39, 35, 42),
    headings_style=headings_style,
    line_height=6,
    text_align=("LEFT", "CENTER", "RIGHT", "RIGHT"),
    width=160,
) as table:
    # 若有表头可在此处添加
    # header_row = table.row()
    # header_row.cell("列1")
    # ...
    for idx, data_row in enumerate(data):
        row = table.row()
        # 奇数行填充指定颜色(可根据需求调整索引判断逻辑)
        if idx % 2 == 1:
            row.set_fill_color(224, 235, 255)
        # 逐个添加单元格内容
        for item in data_row:
            row.cell(item)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:50:05