如何为Python Dash中to_html生成的DataFrame设置单列可编辑?
实现colH列可编辑的方案
pandas的to_html方法没有直接支持列级可编辑的参数,我们可以通过自定义格式化函数,把colH列的单元格转换成可编辑的<input>标签来实现需求。
修改步骤:
- 新增一个针对colH列的格式化函数,将单元格内容转为带默认值的输入框
- 把这个函数添加到格式字典
format_dict中,对应colH列
修改后的完整代码:
import pandas as pd from IPython.core.display import display,HTML import os pd.set_option('display.max_colwidth', 0) MP = 'GB' df = pd.DataFrame( [ (1, 'Hello', 158, True, 'Extract-Text-from-Image-using-Python-840x400',""), (2, 'Hey', 567, False, 'sampletext1-ocr',""), (3, 'Hi', 123, False, 'sampletext2-ocr',""), (4, 'Howdy', 578, True, 'sampletext3-ocr',""), (5, 'Hello', 418, True, 'image-10',""), (6, 'Hi', 98, False, 'image-9',""), ], columns=['colA', 'colB', 'colC', 'colD', 'colE', 'colH'] ) def categorise(row): return f"https://pyshark.com/wp-content/uploads/2022/05/{row['colE']}.png" df['colF'] = df.apply(lambda row: categorise(row), axis=1) images1 = df['colF'].values.tolist() df['colG'] = images1 # convert your links to html tags def path_to_image_html(path): return '<img src="'+ path + '" width="60" >' # 新增:colH列的可编辑格式化函数 def editable_cell(value): return f'<input type="text" value="{value}" style="width:100%;border:none;" />' pd.set_option('display.max_colwidth', None) image_cols = ['colG'] #<- define which columns will be used to convert to html # Create the dictionary to be passed as formatters format_dict = {} for image_col in image_cols: format_dict[image_col] = path_to_image_html # 新增:将colH的格式化函数加入字典 format_dict['colH'] = editable_cell a = HTML(df.drop(['colF'], axis=1).to_html(escape=False ,formatters=format_dict)) with open("assets/data.html", "w") as file: file.write(a.data)
说明:
- 自定义的
editable_cell函数会把colH的每个单元格转为一个文本输入框,默认值为原单元格内容,样式设置为无边框、宽度100%,和原表格单元格风格一致 - 生成的
data.html中,只有colH列的单元格可以直接编辑,其他列保持原有状态 - 如果需要保存编辑后的数据,你需要额外添加JavaScript代码来捕获输入框的变化并提交,或者结合后端逻辑处理
内容的提问来源于stack exchange,提问作者Sanket Sathe
相关产品推荐
相关产品推荐

