Python onclick按钮小部件返回对象
我正试图用python在jupyter笔记本中构建一个文件/数据选择器。我的想法是使用multipleSelect小部件在文件中选择一些文件和数据通道,然后使用按钮返回数据帧 如何访问df_对象Python onclick按钮小部件返回对象,python,ipywidgets,Python,Ipywidgets,我正试图用python在jupyter笔记本中构建一个文件/数据选择器。我的想法是使用multipleSelect小部件在文件中选择一些文件和数据通道,然后使用按钮返回数据帧 如何访问df_对象 #stack example from ipywidgets import widgets from IPython.display import display from IPython.display import clear_output import pandas as pd import nu
#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()
您确实应该为此使用一个类,然后将所有函数定义为作用于该类的实例。并不是所有这些都需要公开访问。您还可以将
df_对象
存储在单独的属性(如字典)中,并使用单独的函数访问字典。查看下面的代码:
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\u df\u objects()
将返回一个字典,其中包含所需的“文件:dataframe\u of\u file
”键值对
希望这有帮助:)看起来您忘记问问题了……您想将数据帧返回到哪里?想要的行为是什么?想知道您是否可以看看我的问题,这也是创建类所必需的。尝试调整您的解决方案,但对
class