[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

open. Because of that, you can never make more than one copy of the pop up on-screen
at once, as shown in Figure 8-19.


Figure 8-19. A modal custom dialog at work


In fact, the call to the dialog function in this script doesn’t return until the dialog
window on the left is dismissed by pressing its OK button. The net effect is that modal
dialogs impose a function call–like model on an otherwise event-driven programming
model; user inputs can be processed right away, not in a callback handler triggered at
some arbitrary point in the future.


Forcing such a linear control flow on a GUI takes a bit of extra work, though. The secret
to locking other windows and waiting for a reply boils down to three lines of code,
which are a general pattern repeated in most custom modal dialogs.


win.focus_set()
Makes the window take over the application’s input focus, as if it had been clicked
with the mouse to make it the active window. This method is also known by the
synonym focus, and it’s also common to set the focus on an input widget within
the dialog (e.g., an Entry) rather than on the entire window.


win.grab_set()
Disables all other windows in the application until this one is destroyed. The user
cannot interact with other windows in the program while a grab is set.


win.wait_window()
Pauses the caller until the win widget is destroyed, but keeps the main event-
processing loop (mainloop) active during the pause. That means that the GUI at
large remains active during the wait; its windows redraw themselves if covered and
uncovered, for example. When the window is destroyed with the destroy method,
it is erased from the screen, the application grab is automatically released, and this
method call finally returns.


Because the script waits for a window destroy event, it must also arrange for a callback
handler to destroy the window in response to interaction with widgets in the dialog
window (the only window active). This example’s dialog is simply informational, so
its OK button calls the window’s destroy method. In user-input dialogs, we might
instead install an Enter key-press callback handler that fetches data typed into an
Entry widget and then calls destroy (see later in this chapter).


Dialogs | 441
Free download pdf