Search code examples
pythontkintereventsevent-handling

ModX in event.state in tkinter?


I've been figuring out how to parse tkinter events via event.state to reduce the number of times that I have to call root.bind() (e.g., I can avoid binding both "<ButtonPress-1>" and "<Shift-ButtonPress-1>" by finding if shift was pressed via event.state). Of course, I've relied heavily on the tkinter source code (specifically the definition for __repr__, starting on line 234) to convert the integer of event.state to something I can understand:

def getStatefromInt(state_int):
    # from https://github.com/python/cpython/blob/3.8/Lib/tkinter/__init__.py
    if isinstance(state_int, int):
        state = state_int
        mods = ('Shift', 'Lock', 'Control',
                'Mod1', 'Mod2', 'Mod3', 'Mod4', 'Mod5',
                'Button1', 'Button2', 'Button3', 'Button4', 'Button5')
        s = []
        for i, n in enumerate(mods):
            if state & (1 << i):
                s.append(n)
        state = state & ~((1<< len(mods)) - 1)
        if state or not s:
            s.append(hex(state))
        return s

One of the things that keeps coming up out of state when events occur is Mod1. What do Mod1 and the other ModX states represent? I thought the number might correspond to the type of button press, but all types of mouse clicks cause only Mod1. I have not been able to find information on what this means online, and I'm having a hard time seeing from the source code what it might mean.


Solution

  • ModX represents a modification, a Modifier Key.

    In computing, a modifier key is a special key (or combination) on a computer keyboard that temporarily modifies the normal action of another key when pressed together. By themselves, modifier keys usually do nothing; that is, pressing any of the ⇧ Shift, Alt, or Ctrl keys alone does not (generally) trigger any action from the computer.

    Tkinter is a crossplatform GUI-Toolkit and uses system specific facilities. Different OS using different methods, for example a PC that runs Linux signals Alt Gr as Mod 5 while a PC running Windows signals the same keystroke as Control-Alt. You can look at the Modifier Keys on tcl-lang.ord.

    Event.state is a bit mask indicating which of certain modifier keys and mouse buttons were down or active when the event triggered and is not reliable because of the system specific facilities as pointed out here.