Access variables defined in a function in Python

不羁的心 提交于 2020-01-16 11:26:11

问题


I am defining an ipywidget button with the objective to run a function when the user clicks on it:

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)

Where nameS2 is:

['S2A_MSIL2A_20191205T110431_N0213_R094_T30TVK_20191205T123107.zip',
 'S2B_MSIL2A_20191203T111329_N0213_R137_T30TVL_20191203T123004.zip']

This code works in the way that when clicking on the button dfS2 gets printed since I am using the print command. However, I want to display the dataframe as variable (witouth calling `print).

def whenclick2(b):
    if catalogue.selected_index+1 ==2:
        dfS2 = pd.DataFrame({'Name': nameS2})
        dfS2

Button.on_click(whenclick2)

When using this second option and clcking on the button, nothing gets delivered. I have tried to use return dfS2 for example, and many other apporaches (global variables, etc.) like :

if catalogue.selected_index+1 ==2:
    def whenclick(b):
        dfS2 = pd.DataFrame({'Name': nameS2})
        return dfS2

Button.on_click(whenclick)

But I always get no output when clicking my button. Any idea on this? I have been checking the examples in the ipywidget documentation but trying to simulate the same in my case did not work https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html

-- EDIT --

Based on @skullgoblet1089 answers, I am trying the following code:

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)

However, when clicking on the button nothing gets displayed.


回答1:


Use the global keyword:

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)

It will declare (if not exist) and assign value to variable in global namespace for module.



来源:https://stackoverflow.com/questions/59412860/access-variables-defined-in-a-function-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!