How to detect that a key is being pressed, not HAS been pressed earlier!??

Jeff Epler jepler at
Wed Jan 28 20:23:22 CET 2004

In Tk, each event has a 'state' field, which can tell you whether
modifier keys or mouse buttons were pressed when an event was received.
Note that for the KeyPress event which is a modifier key, the state
field will not reflect the newly pressed key (the same goes for button
presses), as implied by this section of the XKeyEvent manpage:

       The state member is set to indicate the logical state of the pointer
       buttons and modifier keys just prior to the event, which is the bitwise
       inclusive OR of one or more of the button or modifier key masks: But-
       ton1Mask, Button2Mask, Button3Mask, Button4Mask, Button5Mask, Shift-
       Mask, LockMask, ControlMask, Mod1Mask, Mod2Mask, Mod3Mask, Mod4Mask,
       and Mod5Mask.

from Tkinter import *

# for pre-2.3 versions
#def enumerate(l):
#    for i in range(len(l)): yield i, l[i]

# Set up a mapping from bits to names
# (I'm not sure if these values match on Windows)
names = "Shift Caps Control Alt Num Mod3 Mod4 Mod5 1 2 3 4 5".split()
mods = [(1<<i, v) for i, v in enumerate(names)]

# Here's a handler that gets various events and looks at the state field
def setModifiers(event):
    s = []
    for i, v in mods:
        if event.state & i: s.append(v)
    if not s: s = ['(none)']
    var.set(" ".join(s))

# Set up a minimal user interface
t = Tk()
var = StringVar(t)
l = Label(t, textv = var, width=32)

# including a couple of bindings (the text will update when
# one of these bindings is triggered)
for binding in "<Motion> <1> <ButtonRelease-1>".split():
    l.bind(binding, setModifiers)


More information about the Python-list mailing list