【问题标题】:List output from function on ipywidgets列出 ipywidgets 上函数的输出
【发布时间】:2019-01-20 17:52:41
【问题描述】:

我构造了一个链接到 MySQL 的函数,它返回给定父 ID 的子列表。我想使用 ipywidgets 输出这个孩子的列表。

我无法将函数链接到 ipywidgets。到目前为止,我有:

> from ipywidgets import widgets
> 
> text1 = widgets.Text() 
> text2 = widgets.Text() 
> button = widgets.Button(description = 'Run')

> display(text1) 
> display(button) display(text2)
> 
> idnum = text1.value 
> text2.value= list_children(idnum)    
> 
> button.on_click(list_children)

函数如下:

> def list_children(parentid):
>     value = parentid
>     parent_80 = session.query(Parent).get(value) 
>     parent_80_children= parent_80.children
>     childrenlist=[] 
>     
>     for i in parent_80_children:
>         childrenlist.append(i.UWI)
>         
>     return childrenlist

我不断收到以下错误:

AttributeError: 'NoneType' 对象没有属性 'children'

因为它打破了这一行:

parent_80_children= parent_80.children

如果我运行 python 单元,该函数是正确的,所以我知道它正在工作,但是当我尝试单击小部件框“运行”时它会中断。不知何故,函数和小部件框之间没有链接。

我希望在单击“运行”小部件按钮时得到如下输出:

  • 1771860100
  • 1771860200
  • 1771860300

减去要点。

感谢任何输入。

【问题讨论】:

    标签: function user-interface button display ipywidgets


    【解决方案1】:

    当您使用按钮的.on_click() 方法时,您需要指定您要运行的功能,您已正确完成。但是,当您单击按钮时,按钮实例本身会传递给函数。这就解释了为什么当您单击按钮时会看到该错误。该函数认为它正在获取一个parentid(可能是一个字符串或整数),但实际上却收到了一个ipywidgets.Button 的实例!

    假设您想像在代码的上半部分那样获取 text1 小部件中的文本,您需要将 Text 小部件传递给函数。因此,将其添加到您的 on_click() 调用中,使用 partial 将文本字段指定为参数。文本小部件将是第一个参数,Button 实例将作为第二个参数。如果您忘记在编写函数定义时传递了 Button 实例,您将收到类似“仅采用 1 个参数但已给出 2 个参数”的错误。

    希望您可以参考下面的示例并进行修改以满足您的需求。


    import ipywidgets as widgets
    from functools import partial
    
    text1 = widgets.Text()
    
    def list_children(text_field, button):
        print(text_field.value)
    
    button = widgets.Button()
    
    button.on_click(partial(list_children, text1))
    display(text1, button)
    

    【讨论】:

    • 感谢您的详尽解答!我让它工作了。
    猜你喜欢
    • 2021-01-23
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    相关资源
    最近更新 更多