访问Python函数中定义的变量
我定义了一个访问Python函数中定义的变量,python,function,variables,printing,widget,Python,Function,Variables,Printing,Widget,我定义了一个ipywidget按钮,目标是在用户单击时运行函数: import ipywidgets as widgets Button = widgets.Button(description='Search', disabled=False, button_style='info', tooltip='Search') display(Button) def whenclick(b): if catalogue.selected_index+1 ==2: dfS2
ipywidget按钮
,目标是在用户单击时运行函数:
import ipywidgets as widgets
Button = widgets.Button(description='Search', disabled=False, button_style='info', tooltip='Search')
display(Button)
def whenclick(b):
if catalogue.selected_index+1 ==2:
dfS2 = pd.DataFrame({'Name': nameS2})
print(dfS2)
Button.on_click(whenclick)
其中nameS2
是:
['S2A_MSIL2A_20191205T110431_N0213_R094_T30TVK_20191205T123107.zip',
'S2B_MSIL2A_20191203T111329_N0213_R137_T30TVL_20191203T123004.zip']
由于我使用的是print
命令,因此当单击按钮dfS2
时,此代码的工作方式是打印。但是,我想将数据帧
显示为变量(不调用`print)
当使用第二个选项并点击按钮时,不会传递任何内容。例如,我尝试使用返回dfS2
和许多其他方法(全局变量等),如:
但是当我点击我的按钮时,我总是没有得到任何输出。有什么想法吗?我一直在检查ipywidget
文档中的示例,但尝试在我的案例中模拟相同的示例并不奏效
--编辑--
基于@skullgoblet1089答案,我正在尝试以下代码:
import ipywidgets as widgets
Button = widgets.Button(description='Search', disabled=False, button_style='info', tooltip='Search')
display(Button)
def whenclick2(b):
global data_frame_to_print
if catalogue.selected_index+1 ==2:
dfS2 = pd.DataFrame({'Name': nameS2})
data_frame_to_print = dfS2.copy()
dfS2
Button.on_click(whenclick2)
但是,单击按钮时,不会显示任何内容。使用关键字:
def当CLICK2(b)时:
全局数据帧到打印
如果所选目录索引+1==2:
dfS2=pd.DataFrame({'Name':nameS2})
数据\u帧\u到\u打印=dfS2.copy()
dfS2
按钮。单击(当单击2时)
它将声明(如果不存在)并为模块的全局命名空间中的变量赋值。使用global
关键字使变量成为全局变量。或者使用类在适当的上下文中封装类/实例级变量。@skullgoblet1089请添加解决方案的代码示例。python新手,我不确定我是否完全理解您所说的封装类。谢谢,我试过你的代码(我编辑了这个问题,让你知道我运行的代码),当点击按钮时,什么都没有显示。我错过什么了吗?我正在一个Jupyter笔记本上工作,如果这是相关的,这段代码将在全局上下文中为您提供一个句柄,然后您可以在函数调用之外使用该句柄,随时将变量打印到交互式控制台。我建议这样做是因为我假设您希望在事件发生后在不同的单元格中以交互方式检查df的值,实际上我希望在同一单元格中运行所有内容。单击按钮,然后在另一个代码单元格中调用dfS2
时,我得到name未定义dfS2
错误。。。。我遗漏了什么吗?实际上,我必须在other中添加返回dfS2
,以便能够在新的jupyter代码单元中调用该变量。这部分是我想要的,但最终目标是在单击按钮时显示dfS2
,而不需要在新单元格中调用变量。对此有何评论?根据另一篇文章-似乎类的解决方案是可以选择的。这就是你在评论@skullgoblet1089中提到的吗
if catalogue.selected_index+1 ==2:
def whenclick(b):
dfS2 = pd.DataFrame({'Name': nameS2})
return dfS2
Button.on_click(whenclick)
import ipywidgets as widgets
Button = widgets.Button(description='Search', disabled=False, button_style='info', tooltip='Search')
display(Button)
def whenclick2(b):
global data_frame_to_print
if catalogue.selected_index+1 ==2:
dfS2 = pd.DataFrame({'Name': nameS2})
data_frame_to_print = dfS2.copy()
dfS2
Button.on_click(whenclick2)