配置 tkinter 小部件时出错:'NoneType' 对象没有属性

Error when configuring tkinter widget: 'NoneType' object has no attribute

我运行正在使用下面的代码,当我硬编码值

时运行很好
from nsetools import Nse
nse = Nse()
with open('all_nse_stocks') as nse_stocks:
    for stock in nse_stocks:
        q = nse.get_quote('INFY')
        print q.get('open'), '\t', q.get('lastPrice'), '\t', q.get('dayHigh'), '\t', q.get('dayLow')

看到我已经硬编码了值 nse.get_quote('INFY') 但是当我 运行 以下代码时,出现以下错误:

from nsetools import Nse
nse = Nse()
with open('all_nse_stocks') as nse_stocks:
    for stock in nse_stocks:
        q = nse.get_quote(stock)
        print q.get('open'), '\t', q.get('lastPrice'), '\t', q.get('dayHigh'), '\t', q.get('dayLow')

错误:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    print q.get('open'), '\t', q.get('lastPrice'), '\t', q.get('dayHigh'), '\t', q.get('dayLow')
AttributeError: 'NoneType' object has no attribute 'get'

请帮忙

NoneType object has no attribute ... 表示您有一个 None 的对象,并且您正在尝试使用该对象的属性。

在您的情况下,您正在做 q.get(...),因此 q 必须是 None。由于 q 是调用 nse.get_quote(...) 的结果,因此该函数必须有返回 None 的可能性。您需要调整您的代码以考虑到这种可能性,例如在尝试使用它之前检查结果:

q = nse.get_quote(stock)
if q is not None:
    print ...

问题的根源可能在于您读取文件的方式。 stock 将包含换行符,因此您应该在调用 nse.get_quote:

之前将其删除
q = nse.get_quote(stock.strip())

请检查'stock'的类型 q = nse.get_quote(股票)

必须是字符串。此外,nestools 仅在 Python2 上受支持,您尚未说明您的 python 版本。

如果您在阅读本文时仍然遇到问题,请告诉我。