Getting contents of Text / Entry widgets

Timothy R Evans tre17 at pc142.cosc.canterbury.ac.nz
Tue Jul 6 20:45:23 EDT 1999


catlee at my-deja.com writes:

> Hi,
> 
> I'm writing a little utility that uses a Tkinter Text widget (and an
> Entry widget).  I want to perform an action for every key that is
> entered.  So I do something like:
> 
> def callback(event):
>    print event.widget.get()
> 
> widget=Entry()
> widget.bind("<Key>",callback)
> 
> The problem with this is that the output generated by callback is
> always one character behind.  I assume this is because when the event
> is generated, the character you've typed hasn't been entered into the
> buffer yet.  I could modify callback to look something like:
> def callback(event):
>    print event.widget.get() + event.char
> 
> But this doesn't handle backspace and delete characters well.
> 
> Is there a nice way of retrieving the contents of a Text / Entry widget
> every time the widget's text buffer is changed (as opposed to whenever
> a key is pressed)?
> 
> Thanks,
> Chris
> 
> 
> Sent via Deja.com http://www.deja.com/
> Share what you know. Learn what you don't.

The class below does this, see the example at the bottom of the script
for how to use it.  This example just prints the contents of the entry
widget.

==============================================================
#!/usr/bin/python

from Tkinter import *

class CallbackEntry(Entry):
    '''Replacement of Entry widget.  Set the "callback" attribute to
    your function, which will be called whenever the entry widget
    changes and will be passed the new contents of the widget'''

    def __init__(self, *args, **kw):
        apply(Entry.__init__, (self,)+args, kw)
        self.stringvar = StringVar(self)
        self.stringvar.trace_variable('w', self.changed)
        self.configure(textvariable=self.stringvar)
        self.callback = None

    def changed(self, *args):
        'Note that the args given to this method are useless'
        if self.callback != None:
            self.callback(self.stringvar.get())

if __name__ == '__main__':
    def test(string):
        print string
    mw = Tk()
    e = CallbackEntry(mw)
    e.pack()
    e.callback = test
    mw.mainloop()

==============================================================
--
Tim Evans




More information about the Python-list mailing list