首页 > 解决方案 > Python面板按钮回调函数

问题描述

所以,我正在尝试使用 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)

所以,显而易见的问题是¿我错过了什么?¿如何使用按钮小部件实现回调?

标签: pythonpandaswidgetpanel-pyviz

解决方案


定义回调的方式是可以的,尽管我不明白为什么要使用关键字save和返回值来定义回调。

以下简化代码在按下按钮时触发回调:

# the key word 'save' can never be changed when the callback is triggered.
def update(event, save=True): 
    print(event)
    return save # which variable should take and use the return value? The calling Button?

button = pn.widgets.Button(name='Button')
button.on_click(update)

# using a bokeh server inside the notebook the print statements in the method 'update' are displayed,
# Otherwise the print statements are not visible in the outout cell
layout = button
layout.app() 

输出是:

<bokeh.server.server.Server at 0x29194b0e6c8>
Event(what='value', name='clicks', obj=Button(clicks=1), cls=<class 'panel.widgets.button.Button'>, old=0, new=1, type='changed')

推荐阅读