访问在Python中的函数中定义的变量 [英] Access variables defined in a function in Python

查看:62
本文介绍了访问在Python中的函数中定义的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在定义一个 ipywidget按钮,其目的是在用户单击它时运行一个函数:

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)

其中 nameS2 是:

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

此代码的工作方式是:单击按钮 dfS2 时,由于我正在使用 print 命令,因此该代码得以打印.但是,我想将 dataframe 显示为变量(不调用`print).

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)

使用第二个选项并按一下按钮时,不会传递任何内容.例如,我尝试使用 return dfS2 和许多其他方法(例如 global 变量等):

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)

但是当我单击按钮时,我始终没有任何输出.有什么想法吗?我一直在检查 ipywidget 文档中的示例,但在我的情况下尝试对它们进行模拟无法正常工作

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

-编辑-

基于@ skullgoblet1089的答案,我正在尝试以下代码:

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.

推荐答案

使用 全局 关键字:

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.

这篇关于访问在Python中的函数中定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆