Ошибка nonetype object has no attribute get

I am writing a function that takes a textbox object from the tkinter library as an argument. When I fill in the textbox and hit the button, I get

"AttributeError: 'NoneType' object has no attribute 'get'." 

I know for a fact the textbox object has get() as a function. I even imported the tkinter library into the file that has my function. Here’s a simplified version of what I am trying to do in two files:

main:

import tkinter
import save_file
app = tkinter.Tk()
textbox = tkinter.Text(app).pack()
button = tkinter.Button(app, command=lambda: save_file.save_file(textbox))

save_file:

import tkinter
def save_file(textbox):
    text = textbox.get()

Can anyone tell me what I am doing wrong?

asked Oct 24, 2014 at 22:12

user3291465's user avatar

1

pack() returns None; you want to store just the Text() object, then call pack() on it separately:

textbox = texinter.Text(app)
textbox.pack()

answered Oct 24, 2014 at 22:14

Martijn Pieters's user avatar

Martijn PietersMartijn Pieters

1.0m295 gold badges4031 silver badges3325 bronze badges

2

tkinter.Text(app).pack() returns None so you set textbox equal to None

Change to:

 textbox = tkinter.Text(app)
 textbox.pack()

answered Oct 24, 2014 at 22:14

Padraic Cunningham's user avatar

Your problem is that the .pack() method on a tkinter Text object returns None.

The fix:

import tkinter
import save_file
app = tkinter.Tk()
textbox = tkinter.Text(app)
textbox.pack()
button = tkinter.Button(app, command=lambda: save_file.save_file(textbox))

answered Oct 24, 2014 at 22:15

BingsF's user avatar

BingsFBingsF

1,25910 silver badges15 bronze badges

Table of Contents
Hide
  1. What is AttributeError: ‘NoneType’ object has no attribute ‘get’?
  2. How to fix AttributeError: ‘NoneType’ object has no attribute ‘get’?
    1. Solution 1 – Call the get() method on valid dictionary
    2. Solution 2 – Check if the object is of type dictionary using type
    3. Solution 3 – Check if the object has get attribute using hasattr
  3. Conclusion

The AttributeError: ‘NoneType’ object has no attribute ‘get’ mainly occurs when you try to call the get() method on the None value. The attribute get() method is present in the dictionary and must be called on the dictionary data type.

In this tutorial, we will look at what exactly is AttributeError: ‘NoneType’ object has no attribute ‘get’ and how to resolve this error with examples.

If we call the get() method on the None value, Python will raise an AttributeError: ‘NoneType’ object has no attribute ‘get’. The error can also happen if you have a method which returns an None instead of a dictionary or if we forget the return statement in the function as shown below.

Let us take a simple example to reproduce this error.

# Method return None instead of dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}


data = fetch_data()
print(data.get("name"))

Output

AttributeError: 'NoneType' object has no attribute 'get'

In the above example, we have a method fetch_data() which returns an None instead of a dictionary because the return statement is missing.

Since we call the get() method on the None value, we get AttributeError.

We can also check if the variable type using the type() method, and using the dir() method, we can also print the list of all the attributes of a given object.

# Method return None instead of dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}


data = fetch_data()
print("The type of the object is ", type(data))
print("List of valid attributes in this object is ", dir(data))

Output

The type of the object is  <class 'NoneType'>

List of valid attributes in this object is  ['__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
PS C:PersonalIJSCode>

How to fix AttributeError: ‘NoneType’ object has no attribute ‘get’?

Let us see how we can resolve the error.

Solution 1 – Call the get() method on valid dictionary

We can resolve the error by calling the get() method on the valid dictionary object instead of the None type.

The dict.get() method returns the value of the given key. The get() method will not throw KeyError if the key is not present; instead, we get the None value or the default value that we pass in the get() method.

# Method return None instead of dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}
    return output


data = fetch_data()

# Get the  car Name
print(data.get("name"))

Output

Audi

Solution 2 – Check if the object is of type dictionary using type

Another way is to check if the object is of type dictionary; we can do that using the type() method. This way, we can check if the object is of the correct data type before calling the get() method.

# Method return None instead of dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}
    return output


data = fetch_data()

# Check if the object is dict
if (type(data) == dict):
    print(data.get("name"))


softwares = None

if (type(softwares) == dict):
    print(softwares.get("name"))
else:
    print("The object is not dictionary and it is of type ", type(softwares))

Output

Audi
The object is not dictionary and it is of type  <class 'NoneType'>

Solution 3 – Check if the object has get attribute using hasattr

Before calling the get() method, we can also check if the object has a certain attribute. Even if we call an external API which returns different data, using the hasattr() method, we can check if the object has an attribute with the given name.

# Method return None instead of dict
def fetch_data():
    output = {"name": "Audi",  "price": "$45000"}
    return output


data = fetch_data()

# Check if the object is dict
if (hasattr(data, 'get')):
    print(data.get("name"))


# Incase of None value
softwares = None

if (hasattr(softwares, 'get')):
    print(softwares.get("name"))
else:
    print("The object does not have get attribute")

Output

Audi
The object does not have get attribute

Conclusion

The AttributeError: ‘NoneType’ object has no attribute ‘get’ occurs when you try to call the get() method on the None type. The error also occurs if the calling method returns an None instead of a dictionary object.

We can resolve the error by calling the get() method on the dictionary object instead of an None. We can check if the object is of type dictionary using the type() method, and also, we can check if the object has a valid get attribute using hasattr() before performing the get operation.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

При запуске кода и нажатии в окне «Вычислить» выдает ошибку — line 30, in calculate
a = self.a.get()
AttributeError: ‘NoneType’ object has no attribute ‘get’
Можете пожалуйста объяснить в чем проблема?
Заранее спасибо.

from tkinter import*
from math import sqrt

class App(Frame):

    def __init__(self, master):
        super(App, self).__init__(master)
        self.grid()
        self.create_widgets()
    
    def create_widgets(self):
        Label(self,text = 'Коэффициент a').grid(row = 0, column = 0)
        self.a = Entry(self).grid(row = 0, column = 1, sticky = W)
        Label(self,text = 'Коэффициент b').grid(row = 1, column = 0)
        self.b = Entry(self).grid(row = 1, column = 1, sticky = W)
        Label(self,text = 'Коэффициент c').grid(row = 2, column = 0)
        self.c = Entry(self).grid(row = 2, column = 1, sticky = W)
        Button(self, text = "Вычислить", command = self.calculate).grid(row = 3, column = 0)
        Button(self, text = 'Выйти', command = self.quit).grid(row = 4, column = 0)
        self.results = Text(self, width = 40, height = 5, wrap = WORD)
        self.results.grid(row = 5, column = 0, columnspan = 2)
    
    def calculate(self):
        a = self.a.get()
        b = self.b.get()
        c = self.c.get()
        D = b**2 - 4*a*c
        if D < 0:
            message = 'Нет решений'
        elif D > 0:
            x1 = (-b-sqrt(D))/(2*a)
            x2 = (-b+sqrt(D))/(2*a)
            message = 'x1 = ' + str(x1) + 'n'
            message += 'x2 = ' + str(x2)
        elif D == 0:
            x = (-b)/(2*a)
            message = 'x = '+ str(x)
        self.results.delete(0,0, END)
        self.results.insert(0,0, message)


root = Tk()
root.title('Квадратные уравнения')
root.geometry('350x250')
app = App(root)
root.mainloop()

Python AttributeError: NoneType object has no attribute get means that you are trying to call the get() method on a None object.

This error usually occurs when you mistake a None object for something else.

Why this error occurs

To generate this error you can call the get() method from a None object as shown below:

obj = None

result = obj.get("url")  # ❌

Because the obj variable contains a None value, Python responds with the following error message:

Traceback (most recent call last):
  File ...
    result = obj.get("url")
AttributeError: 'NoneType' object has no attribute 'get'

Let’s see how to fix this error next

How to fix ‘NoneType’ object has no attribute ‘get’

get() is a method of the dictionary object that’s used to get the value of a key in a dictionary object.

Here’s an example to use the method:

my_dict = {"name": "Nathan"}

result = my_dict.get("name")

print(result)  # Nathan

The error means you are calling the get() method from a NoneType object instead of a dictionary object.

One way to avoid this error is to check the type of your variable with the isinstance() function.

Add an if-else statement so that you only call the get() method when the variable is a dictionary as follows:

obj = {"name": "Nathan"}

if isinstance(obj, dict):
    print("obj is a dictionary.")
    obj.get("name")  # ✅
else:
    print("obj is not a dictionary.")

If you know that you only get a dictionary object, you can also use the is not None expression to avoid calling get on a NoneType object.

This is especially useful when you are looping over a list of dictionary objects, where you may get one or two elements that have None value:

result = [
    {"name": "Nathan"},
    None,
    {"name": "Lysa"},
    None,
]

for element in result:
    if element is not None:
        print(element.get("name"))

This way, the None values in the list won’t cause an error as they will be skipped.

Now you’ve learned how to fix Python AttributeError: NoneType object has no attribute get. Very nice! 👍

When working with Python, you may encounter an error message like AttributeError: 'NoneType' object has no attribute 'get'. This error is typically caused when you try to access the get method on a NoneType object, which means the object is None and does not have any attributes or methods. In this guide, we will walk you through a step-by-step process to identify and fix this error.

Table of Contents

  1. Understanding the Error
  2. Identifying the Cause
  3. Step-by-Step Solutions
  4. FAQs

Understanding the Error

The AttributeError occurs when you try to access an attribute or method that doesn’t exist on an object. In this specific case, the error message suggests that you are trying to access the get method on a NoneType object.

For example, consider the following code:

data = None
result = data.get("key")

This code will raise an error because data is None and it doesn’t have the get method.

Identifying the Cause

Before diving into the solutions, it’s essential to identify the cause of this error. The error usually occurs in the following scenarios:

  1. You are trying to access an attribute or method on a variable that is not initialized or is set to None.
  2. You are trying to use a method or attribute on a variable that should be an instance of a class or a dictionary, but it’s not.
  3. The object you are trying to access is a result of a function call, and the function is returning None instead of the expected object.

Once you’ve identified the cause, you can proceed to the next section for the step-by-step solutions.

Step-by-Step Solutions

Scenario 1: Uninitialized or None Variable

Solution: Ensure that the variable is initialized with the correct object before trying to access its attributes or methods.

data = {"key": "value"}
result = data.get("key")

Scenario 2: Wrong Object Type

Solution: Verify that you are using the correct object type for the variable. For example, if you expect the variable to be a dictionary, make sure it’s a dictionary.

data = {"key": "value"}  # Ensure it's a dictionary
result = data.get("key")

Scenario 3: Function Returning None

Solution: Check the function that returns the object and ensure that it returns the expected object instead of None.

def get_data():
    return {"key": "value"}

data = get_data()
result = data.get("key")

FAQs

1. What is a NoneType object in Python?

A NoneType object is an object of type None, which represents the absence of a value or a null value. It is the return value when a function does not explicitly return a value.

2. How can I check if a variable is None before using it?

You can use the is keyword to check if a variable is None:

if data is None:
    print("Data is None")
else:
    result = data.get("key")

3. What is the difference between the get method and the square bracket notation for dictionaries?

The get method allows you to provide a default value if the key is not found in the dictionary, whereas the square bracket notation raises a KeyError if the key is not found.

data = {"key": "value"}
result = data.get("non_existent_key", "default_value")  # Returns "default_value"

result = data["non_existent_key"]  # Raises KeyError

4. Can I use the get method on objects other than dictionaries?

The get method is specific to dictionaries in Python. If you want to use a similar method for other objects, you can define your custom class and implement the __getitem__ method.

5. Can I prevent AttributeError by using a try-except block?

Yes, you can use a try-except block to catch the AttributeError and handle it gracefully:

data = None
try:
    result = data.get("key")
except AttributeError:
    print("Data is None or does not have a get method")

However, it’s usually better to check if the variable is None or has the correct object type before trying to access its attributes or methods.

  1. Python AttributeError
  2. Python Dictionaries
  3. Python NoneType

Понравилась статья? Поделить с друзьями:
  • Ошибка nsqlite3query city car driving
  • Ошибка nsis error что это и как исправить
  • Ошибка nsis error launching installer
  • Ошибка nr 5040 мерседес актрос
  • Ошибка np 2239 6 ps vita