访问Python函数中定义的变量

2024-09-28 22:32:13 发布

您现在位置: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)

但是,当点击按钮时,什么也不会显示。你知道吗


Tags: namedataframesearchindexifdefbuttonwidgets
1条回答
网友
1楼 · 发布于 2024-09-28 22:32:13

使用^{}关键字:

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)

它将声明(如果不存在)并为模块的全局命名空间中的变量赋值。你知道吗

相关问题 更多 >