所以,我正在尝试使用 python Panel库构建一个仪表板,到目前为止,除了Button Widget之外,我在创建一些小部件和绘图之间的交互时没有遇到问题。当单击相应的按钮时,我有两个想要执行的功能。
第一个是将一些数据放入 Dataframe 的函数,它是这样的:
import pandas as pd
from datetime import date
import panel as pn
import hvplot.pandas
pn.extension()
def update_df(event, save=True):
# Read data from csv file
df = pd.read_csv('../my_file.csv')
# Check if data is up to date
if df.index[-i] == pd.to_datetime(date.today()):
return df
else:
# This function updates the data from the last date to the current date
df = get_data(df)
if save:
df.to_csv('../my_file.csv')
return df
# Next is to create the button
update_button = pn.widgets.Button(name='Update DF')
# According to the docs, the on_click method should be enough to accomplish my purpose
update_button.on_click(update_df)
# When the button is clicked nothing happens...
pn.Row(update_button)
我也尝试过update_button.param.watch(update_df, 'clicks')
,但没有得到不同的结果。
我希望在单击按钮时触发的另一个功能更复杂,因为涉及更多的小部件,它是这样的:
# This function will be dependent of a list of variables and a integer value
# This values will be taken from two widgets
list_vars = pn.widgets.CrossSelector(value=['A'], options=['A', 'B', 'C', 'D', 'E', 'F', 'G'])
interval = pn.widgets.DiscreteSlider(value=120, options=[365, 240, 120, 60, 30])
# And of course, the button that will make the callback to the function
optimize_button = pn.widgets.Button(name='Optimize!', button_type='primary')
# Next, the function itself
@pn.depends(list_vars.param.value, interval.param.value)
def optimize_vars(list_vars, interval):
# The data is sliced by the variables of interest
temp = df[list_vars]
# A Monte Carlo simulation is made with the temp data, three arrays are returned,
# they have shape n x len(list_vars)
n = 50000
bsr, brr, mop = simulation(temp, interval, n)
# A markdown table in form of string is created, it contains mainly some statistics about
# the arrays returned by the simulation
m = markdown_table(bsr, brr, mop)
# A holoviews Scatterplot is created
plot = mcs_plot(bsr, brr, mop)
return m, plot
# The layout is created, I want it to show the control widgets as well as the markdown table and the
# plot returned by the function above defined, but again, when the button is clicked nothing happens!
pn.Row(pn.Column(pn.Row('# Variables', align='center'),
pn.Column(interval, align='center'),
pn.Column(list_vars, align='center'),
pn.Column(optimize_button, align='center'),
pn.Column(m, align='center')),
plot)
所以,显而易见的问题是¿我错过了什么?¿如何使用按钮小部件实现回调?