zephyr
zephyr

Reputation: 2332

How to wait for response from modal window before continuing using tkinter?

I have a python program in which I've created a few custom modal windows that are children of a top level tkinter window. An example of such a window is below, but I have other, more complicated ones. What I would like to do, but cannot determine how, is to have somewhere that I call this and wait for a response. I've tried something like below, it fails to create the window

modal = ModalWindow(tk.Tk(), 'Title', 'Text')
while modal.choice is None:
    pass
if modal.choice == 'Yes':
    # Do Something

What is the appropriate way to handle this type of thing?

Custom Modal Window Example

class ModalWindow(object):

    def __init__(self, root, title, text):
        self.choice = None

        # Setup the window
        self.modalWindow = tk.Toplevel(root)
        self.modalWindow.title(title)
        self.modalWindow.resizable(False, False)

        # Setup the widgets in the window
        label = ttk.Label(self.modalWindow, text = text, font = '-size 10')
        label.grid(row = 0, column = 0, columnspan = 2, padx = 2, pady = 2)

        but = ttk.Button(self.modalWindow, text = 'Yes', command = self.choiceYes)
        but.grid(row = 1, column = 0, sticky = 'nsew', padx = 2, pady = 5)

        but = ttk.Button(self.modalWindow, text = 'No', command = self.choiceNo)
        but.grid(row = 1, column = 1, sticky = 'nsew', padx = 2, pady = 5)

        self.modalWindow.rowconfigure(1, minsize = 40)

    def choiceYes(self):
        self.choice = 'Yes'
        self.modalWindow.destroy()

    def choiceNo(self):
        self.choice = 'No'
        self.modalWindow.destroy()

Upvotes: 2

Views: 2120

Answers (2)

Bruce David Wilner
Bruce David Wilner

Reputation: 467

I am missing something fundamental here. If the window is application-modal, you're forced to wait: there's nothing programmatic to be done. If you're trying to wait for an event that transpires in a window belonging to ANOTHER application, you're hosed unless you write some thorny OLE code (I assume Windows here, as UNIX way of doing things would never lead one eve to consider such a solution component).

Upvotes: 0

zephyr
zephyr

Reputation: 2332

After some further digging, I found my own answer. The following does what I want. The function wait_window accepts a tkinter window and pauses until that window has been closed.

root = tk.Tk()
modal = ModalWindow(root, 'Title', 'Text')
root.wait_window(modal.modalWindow)
if modal.choice == 'Yes':
    # Do Something

Upvotes: 3

Related Questions