我正在尝试在Jupyter notebook中构建一个用户界面,该界面能够将一个函数与文本小部件和按钮小部件链接起来。
我的函数为给定股票从开始日期到结束日期的股票价格创建了一个图。函数如下所示
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))
我尝试将函数company与box链接如下: box.on_submit(company)
当我在框中写AAPL时,它给出错误"TypeError:类型为'Text‘的对象没有len()“我的目标是创建一个界面,在这个界面中我在框中写下股票的名称(’AAPL‘),然后点击btn,此时股票价格的曲线图就会出现。
任何帮助都是非常感谢的。谢谢。
发布于 2020-09-03 16:00:07
当您使用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
注意:从ipywidgets7.0开始,on_submit
方法已被弃用,最好使用use box.observe()
来创建盒子,并且在创建盒子时要包含continuous_update=False
作为kwarg。使用此方法时,信息字典将传递给您的函数,因此您需要解析出新值并将其打印出来。
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
https://stackoverflow.com/questions/63715939
复制相似问题