Getting contents of Text / Entry widgets

catlee at my-deja.com catlee at my-deja.com
Wed Jul 7 11:52:57 EDT 1999


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()


Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.




More information about the Python-list mailing list