本文介绍了对象没有属性get的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 3.3 中的 tkinter 模块我对此比较陌生并且正在使用输入框.出于某种原因,当我运行以下代码时,我收到一条错误消息,指出 AttributeError: 'NoneType' object has no attribute 'get'.有人可以向我解释为什么吗?我用一个条目做了一个类似的程序,效果很好.

I am working with the tkinter module in python 3.3 I am relatively new to this and am working with entry boxes. for some reason when I run the following code I get an error message saying AttributeError: 'NoneType' object has no attribute 'get'. Could someone explain to me why? I did a similar program with a single entry that workded just fine.

from tkinter import *
master =Tk()
class quad(object):
def __init__(self, ae, be, ce):
    self.ae = ae
    self.be = be
    self.ce = ce

def calculate(self):
    a = self.ae.get()
    b = self.be.get()
    c = self.ce.get()
    A = float(a)
    B = float(b)
    C = float(c)
    D = (-B)/(2*A)
    E = ((B**2 -4*A*C)**(.5))/(2*A)
    first = D + E
    second = D - E
    print(first, "\n", second)
Label(master, text='A=').grid(row=0, column=0)
Label(master, text='B=').grid(row=1, column=0)
Label(master, text='C=').grid(row=2, column=0)
ae = Entry(master).grid(row=0, column=1)
be = Entry(master).grid(row=1, column=1)
ce = Entry(master).grid(row=2, column=1)
model =quad(ae, be, ce)
Button(master, text='submit', width=10, command=model.calculate).grid(row=3, column=1, sticky=W)
mainloop()

推荐答案

仔细查看错误信息:它说了什么?它准确地告诉你问题是什么.它甚至会告诉您行号.

Take a very close look at the error message: what does it say? It is telling you precisely what the problem is. It's even telling you the line number.

AttributeError: 'NoneType' 对象没有属性 'get'

注意它说 'NoneType' 的地方吗?这意味着一些变量是 None 即使你认为它是别的东西.很明显,None 没有名为 get 的方法.所以,你必须问问自己,为什么它是 None?

Notice where it says 'NoneType'? That means that some variable is None even though you think it is something else. And obviously, None doesn't have a method named get. So, you have to ask yourself, why it is None?

您没有在问题中显示它,但错误很可能发生在 ae 变量上(以及 bece 变量).所以问题是,为什么它们None?

You don't show it in your question, but it's likely that the error is happening on the ae variable (and also on the be and ce variables). So the question is, why are they None?

它们是 None 的原因是你这样设置它们:

The reason they are None is that you are setting them like this:

ae = Entry(master).grid(row=0, column=1)

在python中,当你执行x=a().b()时,x得到b()的值.因此,您将 ae 设置为 grid(...) 语句的值,并且 grid 语句始终返回 None.

In python, when you do x=a().b(), x gets the value of b(). Thus, you are setting ae to the value of the grid(...) statement, and the grid statement always returns None.

解决方案是将您的小部件创建与布局分开,即使您不需要保存对 GUI 小部件的引用,这通常也是一种很好的做法:

The solution is to separate your widget creation from layout, which is generally a good practice even if you don't need to save references to the GUI widgets:

ae = Entry(...)
be = Entry(...)
ce = Entry(...)
...
ae.grid(...)
be.grid(...)
ce.grid(...)

这篇关于对象没有属性get的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 07:33