Search code examples
pythontkinterevent-binding

Event binding to detect a grid_remove (Tkinter)


I'm setting up a Tkinter GUI in Python (2.7). There's one place where I plan to create a collection of similar widgets, using grid() and grid_remove() to select which one of them will be visible at a particular spot on the main window. I have a working prototype, but the only behavioral hitch is that when I grid_remove() a widget to hide it, the widget retains focus -- and even responds to keyboard events.

Is there some event binding I can use to automatically detect a grid_remove() and force the widget to pass the focus elsewhere? Or do I have to just put the focus change in the button code that will do the grid_remove() itself?


Solution

  • You want to bind to the <Unmap> event. From the official tcl/tk documentation (bind man page):

    The Map and Unmap events are generated whenever the mapping state of a window changes.

    Windows are created in the unmapped state. Top-level windows become mapped when they transition to the normal state, and are unmapped in the withdrawn and iconic states. Other windows become mapped when they are placed under control of a geometry manager (for example pack or grid).

    A window is viewable only if it and all of its ancestors are mapped. Note that geometry managers typically do not map their children until they have been mapped themselves, and unmap all children when they become unmapped; hence in Tk Map and Unmap events indicate whether or not a window is viewable.