Skip to content
Advertisement

How to wait for result from Tkinter TopLevel window before continuing?

After a user clicks on a button, I want to create a new TopLevel window with suggestions and when user selects his/her suggestion on the toplevel window and clicks the button “Done” I want to destroy the toplevel window and pass the selected result to root window. This is what I want to achieve but until now I am not able to do it properly.

I tried using wait_window on the toplevel window but that didn’t work every time as sometimes it does not return anything or freezes indefinitely.

JavaScript

Advertisement

Answer

The tkinter method wait_window does exactly what you want, though you could also use wait_visibility or even wait_variable. You claim wait_window is unreliable but that method has been a part of tk for decades and I’ve personally never seen it misbehave.

I recommend implementing this with two pieces of code: a class that implements the window itself, and a function which uses the class to display the window and return the selected item.

The following gives an example. Notice that the value self.selection is initialized to None, and then set to a value when the user clicks the “Confirm Selection” button. Also notice that the show method will get this value before destroying the widget so that it can be retrieved even after the widget has been destroyed.

JavaScript

The function to display it might look something like this:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement