title: Access variables defined in a function in Python
body: <p>I am defining an <code>ipywidget button</code> with the objective to run a function when the user clicks on it:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>Where <code>nameS2</code> is: </p>
  
  <pre><code>['S2A_MSIL2A_20191205T110431_N0213_R094_T30TVK_20191205T123107.zip',
   'S2B_MSIL2A_20191203T111329_N0213_R137_T30TVL_20191203T123004.zip']
  </code></pre>
  
  <p>This code works in the way that when clicking on the button <code>dfS2</code> gets printed since I am using the <code>print</code> command. However, I want to display the <code>dataframe</code> as variable (witouth calling `print). </p>
  
  <pre><code>def whenclick2(b):
      if catalogue.selected_index+1 ==2:
          dfS2 = pd.DataFrame({'Name': nameS2})
          dfS2
  
  Button.on_click(whenclick2)
  </code></pre>
  
  <p>When using this second option and clcking on the button, nothing gets delivered. I have tried to use <code>return dfS2</code> for example, and many other apporaches (<code>global</code> variables, etc.) like :</p>
  
  <pre><code>if catalogue.selected_index+1 ==2:
      def whenclick(b):
          dfS2 = pd.DataFrame({'Name': nameS2})
          return dfS2
  
  Button.on_click(whenclick)
  </code></pre>
  
  <p>But I always get no output when clicking my button. Any idea on this? I have been checking the examples in the <code>ipywidget</code> documentation but trying to simulate the same in my case did not work <a href="https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html" rel="nofollow noreferrer">https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Events.html</a></p>
  
  <p>-- EDIT --</p>
  
  <p>Based on @skullgoblet1089 answers, I am trying the following code:</p>
  
  <pre><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)
  </code></pre>
  
  <p>However, when clicking on the button nothing gets displayed.</p>