Python onclick按钮小部件返回对象

时间:2019-02-21 17:35:27

标签: python ipywidgets

我正在尝试使用python在jupyter笔记本中构建文件/数据选择器。我的想法是,我使用multipleSelect小部件选择文件中的一些文件和数据通道,然后通过按钮返回一个dataFrame。

如何访问df_object?

#stack example
from ipywidgets import widgets
from IPython.display import display
from IPython.display import clear_output
import pandas as pd
import numpy as np
filenames = ["file1", "file2"]
file_dict = {
    "file1":pd.DataFrame(np.arange(5)),
    "file2":pd.DataFrame(np.arange(10,15))
}

def data_selection():
    sel_file = widgets.SelectMultiple(description="Files",
    options=filenames)
    display(sel_file)

    button = widgets.Button(description="OK")
    display(button)            

    def on_button_clicked(button):
        clear_output(wait=True) #clears the previous output
        display(sel_file) #displays new selection window
        display(button) #displays new button
        for f in sel_file.value:
            print (f)
            display (file_dict[f])
            #global df_object #would be a solution but not recommended for sure
            df_object = file_dict[f]
            return df_object #doesn't work
    button.on_click(on_button_clicked)

data_selection()    

1 个答案:

答案 0 :(得分:0)

您确实应该为此使用一个类,然后将所有函数定义为对该类的实例起作用。并非所有人都需要公开访问。您还可以将df_objects存储在单独的属性(如字典)中,并使用单独的函数访问字典。看看下面的代码:

class foo(object):

    def __init__(self, file1, file2):
        self.filenames = [file1, file2]
        self.file_dict = {
                file1:pd.DataFrame(np.arange(5)),
                file2:pd.DataFrame(np.arange(10,15))
            }

    def _create_widgets(self):
        self.sel_file = widgets.SelectMultiple(description='Files',
                                               options=self.filenames,
                                               value=[self.filenames[0]],
                                              )
        self.button = widgets.Button(description="OK")
        self.button.on_click(self._on_button_clicked)

    def _on_button_clicked(self, change):
        self.out.clear_output()
        self.df_objects = {}
        with self.out:
            for f in self.sel_file.value:
                print(f)
                display(self.file_dict[f])
                self.df_objects[f] = self.file_dict[f]

    def display_widgets(self):
        self._create_widgets()
        self.out = widgets.Output()  # this is the output widget in which the df is displayed
        display(widgets.VBox(
                            [
                                self.sel_file,
                                self.button,
                                self.out
                            ]
                        )
               )

    def get_df_objects(self):
        return self.df_objects

然后,您可以创建实例并显示小部件,如下所示:

something = foo('a', 'b')
something.display_widgets()

something.get_df_objects()将返回包含必需的“ file:dataframe_of_file”键值对的字典。

希望这会有所帮助:)