0

我是一名正在学习 python 的高中生,我对为什么在这个脚本中收到错误消息感到有点困惑。它应该提示用户输入他们的年龄信息,然后以天、小时和分钟为单位返回信息。我正在使用 Graphics.py 模块来完成此操作。我得到的错误是:

how old are you.py", line 17, in <module>
    years=entry1.getText()
AttributeError: 'NoneType' object has no attribute 'getText'

我知道该模块已正确安装,因为 getText 函数适用于另一个脚本。我的代码如下所示。谢谢你的帮助!

from graphics import*

win=GraphWin('How Old Are You?',250,500)
win.setBackground ('Gray')

entry1= Entry(Point(125,100),10).draw(win)
entry2= Entry(Point(125,200),10).draw(win)
entry3= Entry(Point(125,300),10).draw(win)

Text(Point(125,50),'How many years old are you?').draw(win)
Text(Point(125,150),'What month in the year? (number)').draw(win)
Text(Point(125,250),'How many weeks into the month?').draw(win)
Text(Point(125,25),'When done click outside a box').draw(win)

win.getMouse()

years=entry1.getText()
months=entry2.getText()
days=entry3.getText()

totalDays=(years*365)+(months*30)+(days)
totalHours=((years*365)+(months*30)+(days))*24
totalMinutes=(((years*365)+(months*30)+(days))*24)*60

Text(Point(125,350),totalDays)
Text(Point(125,400),totalHours)
Text(Point(125,450),totalMinutes)
4

1 回答 1

4

我不知道graphics您正在使用的库,但您的错误似乎试图一次完成太多。

你做:

entry1= Entry(Point(125,100),10).draw(win)
entry2= Entry(Point(125,200),10).draw(win)
entry3= Entry(Point(125,300),10).draw(win)

在这里的每一行中,您确实创建了一个对象 - 通过调用Entry(...), 并调用该对象的方法。方法的返回值draw最终存储在变量中。

通常,在 Python 对象中,方法不会返回它们的对象。如果该方法确实执行了draw建议的操作(如名称),它通常会返回None- 这就是这里发生的事情,正如我们在您的错误消息中看到的那样。

所以,你所要做的就是首先创建你的条目,然后调用draw它们的方法:

entry1= Entry(Point(125,100),10)
entry2= Entry(Point(125,200),10)
entry3= Entry(Point(125,300),10)
entry1.draw(win)
entry2.draw(win)
entry3.draw(win)

除此之外,如果您不希望您的代码如此重复,您可以在循环中创建条目并将它们存储在 Python 列表中:

条目 = []

for vpos in (100,200,300):
    entry = Entry(Point(125,vpos),10)
    entries.append(entry)
    entry.draw(win)

Text(Point(125,50),'How many years old are you?').draw(win)
Text(Point(125,150),'What month in the year? (number)').draw(win)
Text(Point(125,250),'How many weeks into the month?').draw(win)
Text(Point(125,25),'When done click outside a box').draw(win)

win.getMouse()

years, months, days = (entry.getText() for entry in entries)
于 2012-10-12T00:26:04.837 回答