Вопрос

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' object has no attribute 'get'

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?

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?

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

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

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.

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(...)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top