Search code examples
pythonpython-3.xtkintertoplevel

How can I make area outside toplevel unclickable?


I want to create a toplevel window in tkinter, and I want the outside area unclickable. So this way, the user cannot click out from the toplevel window, just after it's been destroyed. (And also preventing to be able to create the same window from the root Tk())


Solution

  • Tkinter supports something called a "grab". When you put a grab on a window, all events are funneled through the widget. Even if you click outside the window, the click will register with the window.

    There are two types of grabs: local and global. Local means the grab only works for your application -- you can still click on the desktop, for example. A global grab works for the whole computer. These can be very dangerous because you can completely lock up your UI if you don't provide a way to release the grab.

    To set a local grab you can call grab_set on any widget, and all events will go to that widget. To set a global graph, call grab_set_global.

    A local grab is how tkinter implements modal dialogs -- while the dialog is open it has a local grab so that you must dismiss the dialog before clicking on buttons in the main window.

    Danger Will Robinson! if you are working with global grabs, make sure there's a absolutely foolproof way to release the grab. For example, during development you might use after to release the grab after 15 seconds. Or, bind to the escape key. Always, always test with a local grab first. As a rule of thumb, however, you should avoid using a global grab unless absolutely necessary.