我正在用 Python 编写一个破折号应用程序。我正在使用 dash_tabulator.DashTabulator() 对象来显示数据。只有某些列是可编辑的,我想用不同的背景颜色(或文本颜色)突出显示这些单元格。我创建了一个非常精简的应用程序版本来说明我的问题。
这是我的 simple_dash.py 文件:
import dash
from dash import html
import dash_tabulator
import pandas as pd
# Sample DataFrame
df = pd.DataFrame({
'col1': ['A', 'B', 'C', 'D'],
'col2': [1, 2, 3, 4]
})
app = dash.Dash(__name__)
app.layout = html.Div([
html.Link(href='/assets/styles.css', rel='stylesheet'),
html.Script(src='/assets/custom_tabulator.js'),
dash_tabulator.DashTabulator(
id='table',
columns=[
{
"title": "Column 1",
"field": "col1",
},
{
"title": "Column 2",
"field": "col2",
"editor": "input",
"formatter": "customCellFormatter",
},
],
data=df.to_dict('records'),
options={
"layout": "fitColumns",
}
)
])
if __name__ == '__main__':
app.run_server(debug=True)
这是我的custom_tabulator.js:
console.log('DEBUG: custom_tabulator.js loaded');
function customCellFormatter(cell, formatterParams, onRendered) {
console.log('DEBUG: customCellFormatter called');
if (cell.getColumn().getDefinition().editor === 'input') {
cell.getElement().classList.add('input-cell');
cell.getElement().classList.add('text-color');
}
return cell.getValue();
}
这是我的 styles.css:
.input-cell {
background-color: #00FF00; /* Green background */
}
.text-color {
color: #FF0000; /* Red text */
}
当我运行应用程序时,没有一个单元格具有绿色背景,也没有一个文本是红色的。当我打开浏览器的开发者控制台时,我确实看到了“DEBUG:custom_tabulator.js returned”消息,但我没有看到“DEBUG:customCellFormatter called”消息。所以,我知道我的 javascript 位于正确的位置(在ssets\ 子目录,以及我的 styles.css 文件),我的 .py 文件成功引用了它,但我无法对单元格进行格式化。
我尝试在列定义中定义格式化程序方法。我尝试在制表符选项定义中定义格式化程序方法。我与 Copilot 进行了长时间的循环讨论,并尝试了所有这些建议。
我的实际应用程序更复杂,但这是问题的简化重现。
有人成功设置了 dash_tabulator 中单元格的背景颜色和/或文本颜色吗?
此版本的 dash_tabulator 似乎不支持自定义 JavaScript 格式化程序。但是,我能够利用列上的 cssClass 属性
"cssClass": "input-cell"
现在只有输入列有绿色背景。