The Text Widget

Edward K. Ream edream at tds.net
Sun Mar 3 22:23:50 EST 2002


> I would like to know how to make it so that whenever I insert some text into
> the text widget from inside my program, it is inserted on a new line?

I am assuming you mean Tk text widgets interfaced with Tkinter.  I
believe you can do just about anything with Tkinter, and it may take a
bit of hacking due to missing events and other strangenesses in Tk. 
I'll answer generally here, not being sure of your situation.

First, note that if you bind to a key-press (<Key>) event, when the
event handler is called the Text widget hasn't been changed yet(!) 
Other frameworks provide a "text will change" event and a "text did
change" event, but AFAIK Tk does not.

You could use the "insert" mark or selection to determine where the
keypress would go, but that gets messy in a hurry.  To get around this,
you can use the after_idle tkinter routine to schedule an action that
will be taken _after_ the text is changed.  You can then munge the text
as needed.  BTW, Tk does a good job of suppressing flashes, so this
approach works well.

There are many ways besides "general" key presses (<Key> bindings) that
can cause text to change.  You may want to provide wrappers for your
idle-time code that allow command handlers to indicate that the text has
been changed or is about to be changed.

For examples of how to do lots of things with Tk/tkinter Text widgets,
take a look at Leo's event handlers in leoTree.py: OnBodyKey,
onBodyChanged, onBodyWillChange and idle_body_key.  Leo does lots of
things on every keystroke, including syntax coloring, undo, auto indent,
updating dirty marks etc.  Auto-indent is probably most similar to what
you want.  Note that the bindings themselves are set in leoFrame.py and
in leoTree.py.

Hope this helps.

Edward
--------------------------------------------------------------------
Edward K. Ream   email:  edream at tds.net
Leo: Literate Editor with Outlines
Leo: http://personalpages.tds.net/~edream/front.html
--------------------------------------------------------------------



More information about the Python-list mailing list