graphics.py中的错误消息

时间:2012-10-12 00:19:25

标签: python graphics

我是一名学习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)

1 个答案:

答案 0 :(得分: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列表中:

entries = []

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)