[Tutor] Binding keys without Tk?

Magnus Lycka magnus@thinkware.se
Thu Nov 14 13:05:59 2002


At 00:48 2002-11-14 -0500, Jmllr891@cs.com wrote:
>Is there any way to bind keys to functions in Python without using 
>Tkinter, something that will work for the Windows OS?

Do you mean without a GUI at all?

You can catch keypresses with the msvcrt standard library module.
See the library reference. But if you think of binding keys to
functions like in Tkinter, you probably imagine an event based
program, such as most GUI programs. Then you need an event-loop
which is waiting for events such as key-presses and fires off the
bound functions when they occur. Without a library such as Tkinter
or something similar, I guess you will have to write this on your
own. It's not a big thing for a small program though.

#msvcrtevtdemo.py
import msvcrt, time, sys, os

keys = {}

def dir():
     os.system('DIR')
keys['d'] = dir

def now():
     print time.asctime()
keys['t'] = now

keys['q'] = sys.exit

# Event loop

while 1:
     char = msvcrt.getch()
     try:
         keys[char]()
     except KeyError:
         print char,

Then there are other GUI's than Tkinter, such as wxPython, PythonWin
or AnyGui. It's not clear to me what you really want.



-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se