Entry widget bind problems

Abel Daniel abli at freemail.hu
Wed Apr 2 15:27:18 EST 2003


vector wrote:
> Im a little confused with an entry widget bind. I had it working b4 but 
> In an attempt to tidy up the code I have confused the class/callback 
> reference or something.
> As you can see from the text below, there is a MyFrame instance which 
> builds the TK Gui window, in which a frame contains an entry widget. 
> after typing in text into the entry widget a <return> event(enter key) 
> is supposed to run the doEntry, but all i get this error.
> what am i doing wrong?
 [ ... code snipped ... ]

The short asnwer is that you doEntry is wrong. An event callback will
get (at most) one argument when it is called, which will be an Event
instance. Thats what becomes page in your doEntry function.
This stores all sorts of usefull information, of which the
widget attribute will be important for you, as it is the widget where
the event occured.

Changing that function to:

def doEntry(event):
    """Gets text from Entry widget on <enter> hit"""
    page=event.widget
    p=page.get()       #gets all text
    print p              #print it
    page.delete(0,END)        #clear entry widget

should get it working.

Apart from that it looks like you have the arguments to bind() mixed up.
You use the first and second correctly, however the docs write the
following about the third one:
(ADD is the third argument, FUNC is the second one)
    An additional boolean parameter ADD specifies whether FUNC will
    be called additionally to the other bound function or whether
    it will replace the previous function.

So that is simply to allow multiple bindings to the same event, thereby
doing two different things if an event occurs.

An additional remark:
in the code you posted, entry looks like being a method of a class,
however, you don't use it like that. I would change the name of the
first argument from self to something else (like frame) to avoid
misleading other people who read your code.
On the other hand, what you are doing with entry() and doEntry() is
essentially making a costumized widget with some special functionality,
and that can be done much nicer in OO style. Either subclassing from
Tkinter.Entry, or by making an own class. (In fact, I would think putting
the functionality of entry inside the __init__ of MyFrame would be better,
if you don't use it elsewhere.) This would have the advantage
of being able to do:
   self.outEntry.bind('<Return>', self.doEntry)
(notice that in this case doEntry is a method of a class)
and doEntry might look like this:
    def doEntry(self, event):
        p=self.outEntry.get()       #gets all text
        print p              #print it

Notice that in this case, the class instance was automatically passed to
doEntry, and we can avoid reading the contents of the event instance.
But this is (at least partly) a question of aesthetics.

Abel Daniel





More information about the Python-list mailing list