[Tutor] Tkinter: Deleting text when clicking in field.

Alan Gauld alan.gauld at btinternet.com
Sun Aug 21 01:11:46 CEST 2011

On 20/08/11 20:12, brandon w wrote:
> I worked on this for a long time. I did many searches to fix the many
> error messages I was getting and I finally got this to work. I would now
> just like to have the text disappear when a person clicks in the box to
> type something. How can I do that?

You need to buind the mouse click event to the event handler method. It 
will not be called unless you tell Tkinter to call it.

> from Tkinter import *
> class MyGrid(Frame):
>    def __init__(self, win=None):
>       Frame.__init__(self, win)
>       self.grid()
>       self.mkWidgets()
> [...snip...]
> self.mytext = StringVar()
> self.mytext.set("Enter text here") # This text needs to be deleted upon
> clicking in the field.
> self.e = Entry(bg='orange', textvariable=self.mytext, relief=SUNKEN,
> width=50)
> self.e.grid(row=0, column=0)

You need to add a Bind statement to bind a mouse click to a method that 
clears the text. Remember that everything in a GUI is event driven, so 
you have to link your code to the events.

> I have created a method to clear the field.
> This is not working:
> def clearBox(self):
> self.mytext.delete(0, END)
> return

You need to delete the text in the Entry widget not the StringVar
Alternatively you need to set the StringVar to an empty string and
wait for the widget to redraw itself. (Or force it to redraw!)

Then you need to add a bind statement to tie that method to a mouse 
click in the Entry.

> self.mytext = StringVar(None)
> self.mytext.set("Enter text here")
> self.e = Entry(bg='orange', textvariable=self.mytext, relief=SUNKEN,
> width=50, command=self.clearBox)

That binds the event to the command parameter of the Entry.
BUT the Entry widget does not have a command option - I'm surprised you 
dont get an error complaining about that?

So you need to use the bind() function.
The bind function specifies the event type and the method to be called. 
It expects the method to take an additional event argument:
It should look something like:

# define an event handler
def handleEvent(self, event):
      print "I'm habdling an event"

# bind the button-1 click of the Entry to the handler
self.e.bind('Button-1', handleEvent)


Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list