Getting contents of Text / Entry widgets

Michael P. Reilly arcege at shore.net
Wed Jul 7 16:24:26 EDT 1999


catlee at my-deja.com wrote:
: In article <c75pv252spo.fsf at pc142.cosc.canterbury.ac.nz>,
:   Timothy R Evans <tre17 at pc142.cosc.canterbury.ac.nz> wrote:
:> 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())
:>

: Great!  This works perfectly!  Thanks for your help!  I've come up with
: a replacement for the Text widget.  The same method could be used with
: almost any widget, I imagine.  This doesn't pass the text back to the
: callback function since I only want to know when the text changes, not
: necessarily what it is.

: from Tkinter import *

: class CallbackText(Text):
:    '''Replacement of Text widget.  Set the "callback" attribute to
:    your function, which will be called whenever the text widget
:    changes.'''
:    def __init__(self,*args,**kw):
:       apply(Tkinter.Text.__init__,(self,)+args,kw)
:       self.bind("<Key>",self.active)
:       self.callback=None

:    def active(self,event):
:       self.after_idle(self.idle)

:    def idle(self):
:       if self.callback != None:
:          self.callback()


If you really wanted to "replace" your use of the Text widget, then
you could do the following:

  ### CallbackText.py

  import Tkinter

  class Text(Tkinter.Text):
    # the rest of the class from above

Then in your code, you only have to change:
  from Tkinter import *
  from CallbackText import Text # 'Text' binds to newer widget

None of the code that uses a Text widget would have to change.

  -Arcege





More information about the Python-list mailing list