Search code examples
pythontkintertkmessagebox

What is the correct value to use for the `default` option in tkinter.messagebox`?


I cannot get the default option of tkinter.messagebox to work. May I know what is the correct value to use for the default option?

Sample code:

import tkinter as tk
import tkinter.messagebox as messagebox

root = tk.Tk()

def confirmExit():
    # mbox = messagebox.askokcancel("Quit", "Shut down?", icon="question",
    #                               default="yes")  # don't work
    mbox = messagebox.askokcancel("Quit", "Shut down?", icon="question",
                                  default=tk.YES)  # don't work
    if mbox:
        root.destroy()

root.protocol('WM_DELETE_WINDOW', confirmExit)
root.mainloop()

Error msg 1:

  File "/usr/lib/python3.10/tkinter/messagebox.py", line 76, in _show
    res = Message(**options).show()
  File "/usr/lib/python3.10/tkinter/commondialog.py", line 45, in show
    s = master.tk.call(self.command, *master._options(self.options))
_tkinter.TclError: bad -default value "yes": must be abort, retry, ignore, ok, cancel, no, or yes

Error msg 2:

File "/usr/lib/python3.10/tkinter/messagebox.py", line 76, in _show
    res = Message(**options).show()
  File "/usr/lib/python3.10/tkinter/commondialog.py", line 45, in show
    s = master.tk.call(self.command, *master._options(self.options))
_tkinter.TclError: bad -default value "1": must be abort, retry, ignore, ok, cancel, no, or yes

Solution

  • Since you are using the askokcancel variant, the possible values for default are "ok" and "cancel".

    mbox = messagebox.askokcancel(..., default="ok")
    

    The valid values depend on the type of the dialog. From the official tk documentation, the values for each dialog type are:

    dialog type valid values for default
    abortretryignore "abort", "retry", "ignore"
    ok "ok"
    okcancel "ok", "cancel"
    retrycancel "retry", "cancel"
    yesno "yes", "no"
    yesnocancel "yes", "no", "cancel"