[英]Access variables defined in a function in Python
我正在定义一个ipywidget button
,目的是在用户点击它时运行一个函数:
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
时,此代码的工作方式将被打印。 但是,我想将dataframe
显示为变量(不调用`print)。
def whenclick2(b):
if catalogue.selected_index+1 ==2:
dfS2 = pd.DataFrame({'Name': nameS2})
dfS2
Button.on_click(whenclick2)
当使用第二个选项并点击按钮时,什么也没有传递。 例如,我尝试使用return dfS2
,以及许多其他方法( global
变量等),例如:
if catalogue.selected_index+1 ==2:
def whenclick(b):
dfS2 = pd.DataFrame({'Name': nameS2})
return dfS2
Button.on_click(whenclick)
但是单击我的按钮时总是没有输出。 对此有什么想法吗? 我一直在检查ipywidget
文档中的示例,但在我的情况下尝试模拟相同的示例并没有奏效https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html
- 编辑 -
基于@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)
但是,当单击按钮时,什么也不会显示。
使用global
关键字:
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)
它将声明(如果不存在)并为模块的全局命名空间中的变量赋值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.