Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is wait_window() required for creating a modal dialog in Python Tkinter?

Tags:

python

tkinter

I try to create a modal dialog using Python Tkinter. I found no difference between using and not using wait_window().

import tkinter as tk

def button_click():
  dlg = tk.Toplevel(master=window)

  tk.Button(dlg, text="Dismiss", command=dlg.destroy).pack()

  dlg.transient(window)    # only one window in the task bar
  dlg.grab_set()           # modal
  #window.wait_window(dlg) # why?

window = tk.Tk()

tk.Button(window, text="Click Me", command=button_click).pack()

window.mainloop()

I've seen some examples in that use wait_window() for creating a modal dialog. So I'm not sure whether the function is required for creating a modal dialog.

I'm using Python 3.5.

like image 276
wannik Avatar asked Sep 15 '15 05:09

wannik


2 Answers

Strictly speaking, no, wait_window() is not required to make a modal dialog box. What makes a dialog modal is the grab that you put on the window.

Often, however, once the window is destroyed you may need to run some other code. You can use wait_window() for this purpose, as it will wait for the window to be destroyed before continuing. You can then have code after that, such as a return statement, or some cleanup code. In your case there's nothing to do, so you don't need to call wait_window.

like image 84
Bryan Oakley Avatar answered Oct 19 '22 02:10

Bryan Oakley


running your code using window.wait_window(dlg) won't change anything as dlg.grab_set() already creates a modal dialog. this does only mean that you cannot close window while dlg is still alive. you cannot close window as the modal dialog grabs all mouse events from window and redirects them to null.

If you want to create a modal dialog without grab_set(), you would need to bind all mouse events to one handler and then decide if they should be allowed or dismissed and use wait_window.

As a modal dialog is defined by "is anything outside the dialog and in my application available to be clicked" == False , you already have a modal dialog only using grab_set().

If your application shall not be able to programatically close window, you would need wait_window() as well.

Hope I made everything clear.

like image 45
R4PH43L Avatar answered Oct 19 '22 00:10

R4PH43L