1

I am trying to make a program that will return the user's input and also clear the Entry when Return/Enter is pressed. When ran, the second method (def e_delete(e):) always gives the error, AttributeError: Event instance has no attribute 'delete' and if the e is changed to self no string is returned and no error happens.

from Tkinter import *
import os.path
import PIL.Image, PIL.ImageTk
import Tkinter as tk

def on_change(e):
    inp = e.widget.get()
    print inp

root = tk.Tk()

#Makes a canvas for objects
canvas = Canvas(root, height=100, width=400)
#Displays the canvas
canvas.grid(row=3, column=2)

root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=1)

label = Label(root, text="Enter an element or the atomic number from 1 to 118.").grid(row=0, column=2)

e = tk.Entry(root)
e.pack()
e.bind("<Return>", on_change)
e.grid(row=2, column=2)
e.focus()

def e_delete(e):
    e.delete(0, 'end')

e.bind("<Return>", e_delete)

#img = create_image(0, 300, 'ptable.png')

root.mainloop()
2
  • Can we get a piece of code that doesn't throw 2 errors and a tkinter warning, please? In other words, an actual minimal reproducible example? Commented Mar 28, 2018 at 22:43
  • Also, what's the question? And what does "return the user's input" mean? Return it where? Commented Mar 28, 2018 at 22:45

1 Answer 1

2

You're doing this:

def entry_delete(e):
    e.delete(0, 'end')

The value that gets passed to a callback for an event binding is an Event object. And they don't have a delete method.

The fact that you also have a global variable with the same name doesn't make any difference (except to confuse you and other readers); the parameter e hides the global e.

So, if you want to call a method on your Entry object, don't hide it:

def e_delete(evt):
    e.delete(0, 'end')

Or, if you want to call a method on whatever widget triggered the event (which, in this case, will always be the same thing, so it's just a matter of which one makes more sense to you), you can do that instead:

def e_delete(evt):
    evt.widget.delete(0, 'end')

However, it's usually even better to give everything clear and distinct names to avoid this kind of confusion:

entry = tk.Entry(root)
ent.pack()
entry.bind("<Return>", on_change)
entry.grid(row=2, column=2)
entry.focus()0

def entry_delete(evt):
    entry.delete(0, 'end')

entry.bind("<Return>", entry_delete)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you is much! Now is it possible to get the result from the user as well as delete the entry?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.