微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将jupyter小部件文本框链接到绘制图形的函数

如何解决将jupyter小部件文本框链接到绘制图形的函数

我正在尝试在Jupyter笔记本中构建一个用户界面,该界面能够将一个功能与文本小部件和按钮小部件链接

我的函数为从开始日期到结束日期的给定股票的股价创建图。功能如下

import pandas_datareader as pdr

from datetime import datetime


 def company(ticker):
    strt=datetime(2020,1,1)
    end=datetime.Now()
    dat=pdr.get_data_yahoo(ticker,strt,end)
    return dat['Close'].plot(grid=True)

以下命令绘制苹果股票价格。

company('AAPL')

现在,我按如下所示创建文本和按钮小部件

import ipywidgets as ipw

 Box=ipw.Text(
value='Stock handle',placeholder='Type something',description='String:',disabled=False)


 btn=ipw.ToggleButton(
 value=False,description='Plot',disabled=False,button_style='',# 'success','info','warning','danger' or ''
tooltip='Description',icon='check' # (FontAwesome names without the `fa-` prefix))
    

我尝试将功能公司与Box链接如下: Box.on_submit(公司)

当我在框中编写AAPL时,出现错误“ TypeError:'文本'类型的对象没有len() ” 我的目标是创建一个界面,在该界面中,我在框中输入股票名称(“ AAPL”),然后单击btn,此时将出现股价图。

感谢您的帮助。谢谢。

解决方法

当您使用on_submit附加函数时,整个小部件将作为参数传递给函数(而不仅仅是文本值)。因此,在company函数中,ticker实际上是Text小部件的实例。因此出现错误,因为您无法在小部件上调用len

要获取小部件的文本值,请使用ticker.value,您应该可以调用len

def print_it(ticker):
#     print(len(ticker))  # raises TypeError,you're calling len on the Text widget
    print(len(ticker.value))   # will work,as you're accessing the `value` of the widget which is a string
    
t = ipywidgets.Text(continuous_update=False)
t.on_submit(print_it)
t

NB。 on_submit方法从ipywidgets 7.0开始不推荐使用,最好使用box.observe()创建框,并且在创建框时将continuous_update=False包含在内。使用此方法,信息字典将传递给您的函数,因此您需要解析出新值并打印出来。

def print_it(ticker):
    print(ticker['new'])   # will work,as you're accessing the string value of the widget
    
t = ipywidgets.Text(continuous_update=False)
t.observe(print_it,names='value')
t

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。