Changing the Keyboard output

Jeremy Bowers jerf at
Sun Mar 20 21:20:35 CET 2005

On Sun, 20 Mar 2005 19:30:05 +0000, Abdul Hafiz al-Muslim wrote:

> Hi,
> I am new to Python and still learning.
> I am looking for a way to change the keyboard output within Tkinter - for
> example, say I press "p" and I want to come out as "t".
> Could anyone point me in the right direction?

I'm pretty certain this is not possible in the general case.

One of my persistent pet peeves with GUI toolkits is that it is not
possible to insert your own arbitrary events into the toolkit and get the
toolkit to do *exactly* what it would have done if it had received that
event. While I believe Tk has a "post event" method, it only posts user
events, I do not think you can post system events.

This would completely change the testability and programmability of all
GUI toolkits, radically improving them for agile development... but that's
another rant.

Meanwhile, you've got two options, depending on what you are trying to
do, what platform you are on, and whether you control the target system.
You could actually re-map the keyboard, which all major OSs support,
although that may be too drastic. You could register two event handlers to
the same handling function, so that both "p" and "t" go to the same place.

Finally, if you're working with a Text widget, and you want a "t" to come
out when users press "p", what you do is capture the "p" event (either by
registering "p" or "<Key>"), insert a "t" at the INSERT point, move the
INSERT event forward if you have to, and then cancel the key event by
returning "break". Basically, you are implementing the keypress handler
manually. (To fully emulate the keypress, consider if you want to emulate
the behavior where a keypress destroys the highlighted range, in which
case you need to look at SEL too.) This is a pain, and there are a lot of
cases to cover, but it can be done.

More information about the Python-list mailing list