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

I have run into this issue and I can't understand why.

I took my code from my application and made this test code so you don't have to go through a bunch of junk to see what I am asking.

I have this working in other code. But after comparing the two, I can't for the life of me figure this out.

In this application, I get the error "AttributeError: 'NoneType' object has no attribute 'delete' ".

import Tkinter as tk

def main():
    mainWindow = tk.Tk()
    v = tk.StringVar()
    entryBox = tk.Entry(mainWindow, textvariable=v).grid(column=0, row=1)
    def test():
        entryBox.delete(0,20)
    testButton = tk.Button(mainWindow, text='Go!', command=test, padx=10).grid(row=2, column=0) 
    tk.mainloop()
main()


Solution 1:[1]

The reason this is happening is because you are gridding it in the same variable. If you change your code to the following, it should work:

import Tkinter as tk
def main():
    mainWindow = tk.Tk()
    v = tk.StringVar()
    entryBox = tk.Entry(mainWindow, textvariable=v)
    def test():
        entryBox.delete(0,20)
    testButton = tk.Button(mainWindow, text='Go!', command=test, padx=10)
    testButton.grid(row=2, column=0) 
    entryBox.grid(column=0, row=1)
    tk.mainloop()
main()

The reason this works is because grid() does not return anything.

Solution 2:[2]

The entryBox that you have declared here has not been obtained yet when you are trying to do call delete on that. If you want a simple way to reproduce the error.

In [1]: x = None
In [2]: x.delete
AttributeError: 'NoneType' object has no attribute 'delete'

To fix this you can wrap the entryBox or ensure that it is obtained.

if entryBox:
   entryBox.delete(0, 20)

Solution 3:[3]

entryBox = tk.Entry(mainWindow, textvariable=v).grid(column=0, row=1)

#instead of using in same line you can do like this

entryBox = tk.Entry(mainWindow, textvariable=v) entryBox.grid(column=0, row=1)

Solution 4:[4]

If you want to clear Entry widget, instead of deleting widget content clear the text variable.

text_variable.set("") or v.set("")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 IT Ninja
Solution 2 Senthil Kumaran
Solution 3 Suraj Tiwari
Solution 4 Ayan Khan