The Text Widget
Eric Brunel
eric.brunel at pragmadev.com
Mon Mar 4 09:03:23 EST 2002
Edward K. Ream wrote:
> Are you sure?
Yep. Definitely. In fact, we were doing the same thing than you: a syntax
highlighting text editor. And we never did any after_idle in it, so you can
do it just via regular bindings.
> Note that my main testing was done on Windows, if that
> makes any difference.
It should not: our editor works the same on Windows and Unices.
> If you have an example of fancy bindings for Text widgets I'd love to
> see it. Thanks.
We had indeed to do some bizarre things to be sure that we were informed of
anything that happened to the text. This included for example a custom
management of the X selection (which has a pre-defined binding under X
Windows, but is really hard to catch), and a few other things. We decided
that we would work at the line level: changes are identified on lines (not
at the character level or for the whole text...). Here is a very simplified
example of what we did, just showing how you can catch almost everything
that happens on a Text (a few things may have slipped by in the
simplification, but hopefully not much):
---------------
from Tkinter import *
root = Tk()
t = Text(root)
t.pack()
oldSel = 0
## Prints the current line number and contents
def printCurrentLine(prefix=''):
l, c = t.index(INSERT).split('.', 1)
print '%sCurrent line is %s: "%s"' % \
(prefix, l, t.get("%s.0" % l, "%s.end" % l))
## Called when a key is pressed
def keyPress(event):
global oldSel
printCurrentLine("Before: ")
## Put a custom tag on the selection at the key press
oldSel = 0
t.tag_delete('oldSel')
sel = t.tag_ranges(SEL)
if not sel: return
start, stop = sel[0], sel[1]
t.tag_add('oldSel', start, stop)
oldSel = 1
## Called when a key is released
def keyRelease(event):
printCurrentLine("After: ")
## If the custom tag was set and doesn't exist anymore,
## the selection disappeared
if oldSel and len(t.tag_ranges('oldSel')) == 0:
print "Selection was deleted"
t.bind('<KeyPress>', keyPress)
t.bind('<KeyRelease>', keyRelease)
root.mainloop()
---------------
As I said, there's certainly a few things missing, but starting from that,
you should be able to actually identify every single change that happened
to your text.
HTH
- eric -
More information about the Python-list
mailing list