-2

I am unable to clear a text in my entry box item_rate1.

In another box it deletes text, but in my second box doesn't clear at all. Error shown:

'NoneType' object has no attribute 'delete'

from tkinter import *

window= Tk()
window.geometry("650x250")

def clear_text():
   text.delete(0, END)
   item_rate1.delete(0, END)

rate1 = StringVar()
rate1.set("0")

text= Entry(window, width=40)
text.grid(row=0,column=0)

item_rate1 = Entry(window,textvariable=rate1).grid(row=1,column=0,sticky="w",ipadx=13,padx=35,)

Button(window,text="Clear", command=clear_text, font=('Helvetica bold',10)).grid(row=10,column=0)

window.mainloop()
hc_dev
  • 8,389
  • 1
  • 26
  • 38

1 Answers1

1

the grid() method on Entry does not return the object reference (it returns None)

therefore

item_rate1 = Entry(window,textvariable=rate1).grid(row=1,column=0,sticky="w",ipadx=13,padx=35,)

sets item_rate1 to None, which causes AttributeError: 'NoneType' object has no attribute 'delete' to be thrown in the callback

item_rate1 = Entry(window,textvariable=rate1)
item_rate1.grid(row=1,column=0,sticky="w",ipadx=13,padx=35,)

instead of your one line fixes the problem

ChrisB
  • 1,540
  • 6
  • 20
  • 1
    alternative but not suggested option is to do this (Python 3.8+): `(item_rate1 := Entry(window,textvariable=rate1)).grid(row=1,column=0,sticky="w",ipadx=13,padx=35,)`, this keeps it in one line (probably not compliant with PEP 8, hard to read and stuff (that is why not suggested)) but this will work too – Matiiss Aug 20 '21 at 20:05
  • 2
    Instead of answering this question it's better to leave it as someone has already voted to close it. That way we aren't going to get a lot of repeating information on stackoverflow. – TheLizzard Aug 20 '21 at 20:13