Search code examples
pythontkintertkinter-entrytkinter-button

'NoneType' object has no attribute delete


I have created a program that creates a citation based on entrybox inputs. I am trying to add a button that clears all the entryboxes when clicked; however, I find that the error 'NoneType' object has no attribute delete occurs since none of my entry boxes are packed. When I do replace .place() with .pack(), I find that it works. Is there any way to make this function work with un-padded entry boxes (as I need these boxes in specific locations)?
This is the sample of my code:

from tkinter import *

#create window
win = Tk()
win.geometry("800x500")

#clear function
def clearBoxes():
    author1Input.delete(0,END)

#entry box
author1 = StringVar()
author1Input = Entry(win,textvariable=author1).place(x=30,y=120)

#button to clear
Button(win,text="Clear",command=clearBoxes).place(x=30,y=200)

win.mainloop()

Solution

    • Function def clearBoxes(): needs parameter or else nameInput is not referencing anything. You should pass Entry object as parameter.
    • For whatever reason, having author1Input = Entry(win,textvariable=author1).place(x=30,y=120) in one line messes this up. It needs to be placed after widget has been defined. Someone smarter than me can explain why.

    Here is full solution.

    from tkinter import *
    from functools import partial
    
    #create window
    win = Tk()
    win.geometry("800x500")
    
    #clear function
    def clearBoxes(nameInput):
        nameInput.delete(0,END)
    
    #entry box
    author1 = StringVar()
    author1Input = Entry(win,textvariable=author1)
    author1Input.place(x=30,y=120)
    
    func = partial(clearBoxes, author1Input)
    
    #button to clear
    Button(win,text="Clear",command=func).place(x=30,y=200)
    
    win.mainloop()