-1

I'm trying to clear the Entry widget after the user presses a button using Tkinter.

I tried using EntryPlace.delete(0, END), but I got an error saying that strings don't have the attribute delete.

from tkinter import *

file=open(r'\Users\Armita\Desktop\new file\file_app.txt','a+')

def addline(): 
    file.write(user_entry.get() + '\n') 
    EntryPlace.delete(0, END)

def savechange(): 
    global file
    file.close() 
    file = open(r'\Users\Armita\Desktop\new file\file_app.txt', 'a+')

def saveandclose():
    file.close()
    top.destroy()

top = Tk() 
top.geometry('350x40') 
top.title('Tk')

user_entry = StringVar()
EntryPlace = Entry(top,textvariable=user_entry).grid(row=0,column=0)

AddButton = Button(top,text='add line',command= addline).grid(row=0,column=1)

SaveButton=Button(top,text='save changes',command= savechange).grid(row=0,column=2)

CloseButton1=Button(top,text='save and close',command= saveandclose ).grid(row=0,column=3)

top.mainloop()
JRiggles
  • 4,847
  • 1
  • 12
  • 27

1 Answers1

0

The problem is here:

EntryPlace = Entry(top,textvariable=user_entry).grid(row=0,column=0)

You should declare the Entry and then add it to the grid on separate lines like so:

EntryPlace = Entry(top,textvariable=user_entry)
EntryPlace.grid(row=0,column=0)
# now EntryPlace refers to the actual 'Entry' widget, and not 'None'!

Because grid returns None, as written EntryPlace will always evaluate to None and that can cause all kinds of problems.

The same behavior is true of all the geometry manager methods (pack(), grid(), and place()) so you should get into the habit of separating them from the widget declaration. You'll probably want to do this for all of your other widgets as well to prevent potential issues later.

I would also recommend looking into the Style Guide for Python and perhaps using a linter like flake8. It will help you write better, more readable, and more standardized Python in the long run :)

(for example, CapitalizedNames are typically reserved for classes in Python, while variable names are usually written in snake_case)

JRiggles
  • 4,847
  • 1
  • 12
  • 27