Skip to content

QueryDialog

ttkbootstrap.dialogs.dialogs.QueryDialog (Dialog)

A simple modal dialog class that can be used to build simple data input dialogs. Displays a prompt, and input box, and a set of buttons. Additional data manipulation can be performed on the user input post-hoc by overriding the apply method.

Use a Toplevel widget for more advanced modal dialog designs.

__init__(self, prompt, title=' ', initialvalue='', minvalue=None, maxvalue=None, width=65, datatype=<class 'str'>, padding=(20, 20), parent=None) special

Parameters:

Name Type Description Default
prompt str

A message to display in the message box above the entry widget.

required
title str

The string displayed as the title of the message box. This option is ignored on Mac OS X, where platform guidelines forbid the use of a title on this kind of dialog.

' '
initialvalue Any

The initial value in the entry widget.

''
minvalue Any

The minimum allowed value. Only valid for int and float data types.

None
maxvalue Any

The maximum allowed value. Only valid for int and float data types.

None
width int

The maximum number of characters per line in the message. If the text stretches beyond the limit, the line will break at the word.

65
parent Widget

Makes the window the logical parent of the message box. The messagebox is displayed on top of its parent window.

None
padding Union[int, Tuple[int]]

The amount of space between the border and the widget contents.

(20, 20)
datatype Union[int, str, float]

The data type used to validate the entry value.

<class 'str'>
Source code in ttkbootstrap/dialogs/dialogs.py
def __init__(
    self,
    prompt,
    title=" ",
    initialvalue="",
    minvalue=None,
    maxvalue=None,
    width=65,
    datatype=str,
    padding=(20, 20),
    parent=None,
):
    """
    Parameters:

        prompt (str):
            A message to display in the message box above the entry
            widget.

        title (str):
            The string displayed as the title of the message box.
            This option is ignored on Mac OS X, where platform
            guidelines forbid the use of a title on this kind of
            dialog.

        initialvalue (Any):
            The initial value in the entry widget.

        minvalue (Any):
            The minimum allowed value. Only valid for int and float
            data types.

        maxvalue (Any):
            The maximum allowed value. Only valid for int and float
            data types.

        width (int):
            The maximum number of characters per line in the
            message. If the text stretches beyond the limit, the
            line will break at the word.

        parent (Widget):
            Makes the window the logical parent of the message box.
            The messagebox is displayed on top of its parent
            window.

        padding (Union[int, Tuple[int]]):
            The amount of space between the border and the widget
            contents.

        datatype (Union[int, str, float]):
            The data type used to validate the entry value.
    """
    super().__init__(parent, title)
    self._prompt = prompt
    self._initialvalue = initialvalue
    self._minvalue = minvalue
    self._maxvalue = maxvalue
    self._width = width
    self._datatype = datatype
    self._padding = padding
    self._result = None

apply(self)

Process the data.

This method is called automatically to process the data after the dialog is destroyed. By default, it does nothing.

Source code in ttkbootstrap/dialogs/dialogs.py
def apply(self):
    """Process the data.

    This method is called automatically to process the data after
    the dialog is destroyed. By default, it does nothing.
    """
    pass  # override

create_body(self, master)

Overrides the parent method; adds the message and input section.

Source code in ttkbootstrap/dialogs/dialogs.py
def create_body(self, master):
    """Overrides the parent method; adds the message and input
    section."""
    frame = ttk.Frame(master, padding=self._padding)
    if self._prompt:
        for p in self._prompt.split("\n"):
            prompt = "\n".join(textwrap.wrap(p, width=self._width))
            prompt_label = ttk.Label(frame, text=prompt)
            prompt_label.pack(pady=(0, 5), fill=X, anchor=N)

    entry = ttk.Entry(master=frame)
    entry.insert(END, self._initialvalue)
    entry.pack(pady=(0, 5), fill=X)
    entry.bind("<Return>", self.on_submit)
    entry.bind("<KP_Enter>", self.on_submit)
    entry.bind("<Escape>", self.on_cancel)
    frame.pack(fill=X, expand=True)
    self._initial_focus = entry

create_buttonbox(self, master)

Overrides the parent method; adds the message buttonbox

Source code in ttkbootstrap/dialogs/dialogs.py
def create_buttonbox(self, master):
    """Overrides the parent method; adds the message buttonbox"""
    frame = ttk.Frame(master, padding=(5, 10))

    submit = ttk.Button(
        master=frame,
        bootstyle="primary",
        text=MessageCatalog.translate("Submit"),
        command=self.on_submit,
    )
    submit.pack(padx=5, side=RIGHT)
    submit.lower()  # set focus traversal left-to-right

    cancel = ttk.Button(
        master=frame,
        bootstyle="secondary",
        text=MessageCatalog.translate("Cancel"),
        command=self.on_cancel,
    )
    cancel.pack(padx=5, side=RIGHT)
    cancel.lower()  # set focus traversal left-to-right

    ttk.Separator(self._toplevel).pack(fill=X)
    frame.pack(side=BOTTOM, fill=X, anchor=S)

on_cancel(self, *_)

Close the toplevel and return empty.

Source code in ttkbootstrap/dialogs/dialogs.py
def on_cancel(self, *_):
    """Close the toplevel and return empty."""
    self._toplevel.destroy()
    return

on_submit(self, *_)

Save result, destroy the toplevel, and apply any post-hoc data manipulations.

Source code in ttkbootstrap/dialogs/dialogs.py
def on_submit(self, *_):
    """Save result, destroy the toplevel, and apply any post-hoc
    data manipulations."""
    self._result = self._initial_focus.get()
    valid_result = self.validate()
    if not valid_result:
        return  # keep toplevel open for valid response
    self._toplevel.destroy()
    self.apply()

validate(self)

Validate the data

This method is called automatically to validate the data before the dialog is destroyed. Can be subclassed and overridden.

Source code in ttkbootstrap/dialogs/dialogs.py
def validate(self):
    """Validate the data

    This method is called automatically to validate the data before
    the dialog is destroyed. Can be subclassed and overridden.
    """
    # no default checks required for string data types
    if self._datatype not in [float, int, complex]:
        return True

    # convert result to appropriate data type
    try:
        self._result = self._datatype(self._result)
    except ValueError:
        msg = MessageCatalog.translate("Should be of data type")
        Messagebox.ok(
            message=f"{msg} `{self._datatype}`",
            title=MessageCatalog.translate("Invalid data type"),
            parent=self._toplevel
        )
        return False

    # max value range
    if self._maxvalue is not None:
        if self._result > self._maxvalue:
            msg = MessageCatalog.translate("Number cannot be greater than")
            Messagebox.ok(
                message=f"{msg} {self._maxvalue}",
                title=MessageCatalog.translate("Out of range"),
                parent=self._toplevel
            )
            return False

    # min value range
    if self._minvalue is not None:
        if self._result < self._minvalue:
            msg = MessageCatalog.translate("Number cannot be less than")
            Messagebox.ok(
                message=f"{msg} {self._minvalue}",
                title=MessageCatalog.translate("Out of range"),
                parent=self._toplevel
            )
            return False

    # valid result
    return True