overriding tks text insert method

Joseph Andrew Knapka jknapka at earthlink.net
Mon Sep 3 12:53:47 EDT 2001


Christof Ecker wrote:
> 
> Hi you cracks,
> 
> I want to manipulate the Tkinter Text "insert" method in such a way, that all
> the default bindings use my python method instead.
> 
> If the insert method was programmed in python and not in Tcl, the solution
> would be to subclass text and override the insert method:
> 
> class myText(Text):
>         def insert(self, ... ):
>                 # my stuff
>                 ...
>                 # finally
>                 Text.insert(self, ...)

This should work fine. Tkinter.Text *is* a Python class; its
insert() method just calls into an embedded Tcl interpreter
to do the actual inserting.

Now if you want -keypresses- to be handled by your Python
code, that's a different problem, because the key event
handling happens at the Tcl level and the insert()
method doesn't get called. You can handle that
by binding to the "<Key>" event:

class MyText(Text):

	def __init__(self):
		self.bind("<Key>",self.keyHit)

	def keyHit(self,ev):
		# Process each and every keystroke...

Warning. This approach is littered with traps for the
unwary. I went through this a few days ago while trying to
fix the Tk text-widget bindings in Anygui. You can see how
I handled various problems with this approach by looking
at the latest CVS code from the Anygui project on
SourceForge:

<URL: http://sourceforge.net/projects/anygui>

The relevant code is in anygui/lib/anygui/backends/tkgui.py.
Look at the definition for the TextArea class. My code
is not pretty, but it handles the particular problem
I needed to handle, which was to make a Text widget
selectable and copyable, but not editable (in Tk
disabling a text widget also disables select+copy
bindings, on Windows at least).

You will want to read the Events section of the Tkgui
docs carefully, and the "bind" documentation that comes
with Tcl/Tk.

Cheers,

-- 
# Joe Knapka
# "You know how many remote castles there are along the
#  gorges? You can't MOVE for remote castles!" - Lu Tze re. Uberwald
# Linux MM docs:
http://home.earthlink.net/~jknapka/linux-mm/vmoutline.html



More information about the Python-list mailing list