17. Dialogs

Dialog windows are very similar to standard windows, and are used to provide or retrieve information from the user. They are often used to provide a preferences window, for example. The major difference a dialog has is some prepacked widgets which layout the dialog automatically. From there, we can simply add labels, buttons, check buttons, etc. Another big difference is the handling of responses to control how the application should behave after the dialog has been interacted with.

There are several derived Dialog classes which you might find useful. Gtk.MessageDialog is used for most simple notifications. But at other times you might need to derive your own dialog class to provide more complex functionality.

17.1. Custom Dialogs

To pack widgets into a custom dialog, you should pack them into the Gtk.Box, available via Gtk.Dialog.get_content_area(). To just add a Gtk.Button to the bottom of the dialog, you could use the Gtk.Dialog.add_button() method.

A ‘modal’ dialog (that is, one which freezes the rest of the application from user input), can be created by calling Gtk.Dialog.set_modal on the dialog or set the flags argument of the Gtk.Dialog constructor to include the Gtk.DialogFlags.MODAL flag.

Clicking a button will emit a signal called “response”. If you want to block waiting for a dialog to return before returning control flow to your code, you can call Gtk.Dialog.run(). This method returns an int which may be a value from the Gtk.ResponseType or it could be the custom response value that you specified in the Gtk.Dialog constructor or Gtk.Dialog.add_button().

Finally, there are two ways to remove a dialog. The Gtk.Widget.hide() method removes the dialog from view, however keeps it stored in memory. This is useful to prevent having to construct the dialog again if it needs to be accessed at a later time. Alternatively, the Gtk.Widget.destroy() method can be used to delete the dialog from memory once it is no longer needed. It should be noted that if the dialog needs to be accessed after it has been destroyed, it will need to be constructed again otherwise the dialog window will be empty.

17.1.1. Dialog Objects

class Gtk.Dialog([title[, parent[, flags[, buttons]]])

Creates a new Gtk.Dialog with title title and transient parent parent. The flags argument can be used to make the dialog model (Gtk.DialogFlags.MODAL) and/or to have it destroyed along with its transient parent (Gtk.DialogFlags.DESTROY_WITH_PARENT).

buttons is a tuple of buttons which can be set to provide a range of different buttons and responses. See the add_button() method for details.

All arguments are optional and can be referred to as key-word arguments as well.

get_content_area()

Return the content area of of this dialog.

add_button(button_text, response_id)

Adds a button with the given text (or a stock button, if button_text is a stock item) and sets things up so that clicking the button will emit the “response” signal with the given response_id. The button is appended to the end of the dialog’s action area.

response_id can be any positive integer or one of the predefined Gtk.ResponseType values:

  • Gtk.ResponseType.NONE
  • Gtk.ResponseType.REJECT
  • Gtk.ResponseType.ACCEPT
  • Gtk.ResponseType.DELETE_EVENT
  • Gtk.ResponseType.OK
  • Gtk.ResponseType.CANCEL
  • Gtk.ResponseType.CLOSE
  • Gtk.ResponseType.YES
  • Gtk.ResponseType.NO
  • Gtk.ResponseType.APPLY
  • Gtk.ResponseType.HELP

The button widget is returned, but usually you don’t need it.

add_buttons(button_text, response_id[, ...])

Adds several buttons to this dialog using the button data passed as arguments to the method. This method is the same as calling add_button() repeatedly. The button data pairs - button text (or stock item) and a response ID integer are passed individually. For example:

dialog.add_buttons(Gtk.STOCK_OPEN, 42, "Close", Gtk.ResponseType.CLOSE)
set_modal(is_modal)

Sets a dialog modal or non-modal. Modal dialogs prevent interaction with other windows in the same application.

run()

Blocks in a recursive main loop until the dialog either emits the “response” signal, or is destroyed. If the dialog is destroyed during the call to run(), run() returns Gtk.ResponseType.NONE. Otherwise, it returns the response ID from the “response” signal emission.

17.1.2. Example

_images/dialog_example.png
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from gi.repository import Gtk

class DialogExample(Gtk.Dialog):

    def __init__(self, parent):
        Gtk.Dialog.__init__(self, "My Dialog", parent, 0,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OK, Gtk.ResponseType.OK))

        self.set_default_size(150, 100)

        label = Gtk.Label("This is a dialog to display additional information")

        box = self.get_content_area()
        box.add(label)
        self.show_all()

class DialogWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Dialog Example")

        self.set_border_width(6)

        button = Gtk.Button("Open dialog")
        button.connect("clicked", self.on_button_clicked)

        self.add(button)

    def on_button_clicked(self, widget):
        dialog = DialogExample(self)
        response = dialog.run()

        if response == Gtk.ResponseType.OK:
            print "The OK button was clicked"
        elif response == Gtk.ResponseType.CANCEL:
            print "The Cancel button was clicked"

        dialog.destroy()

win = DialogWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

17.2. MessageDialog

Gtk.MessageDialog is a convenience class, used to create simple, standard message dialogs, with a message, an icon, and buttons for user response You can specify the type of message and the text in the Gtk.MessageDialog constructor, as well as specifying standard buttons.

In some dialogs which require some further explanation of what has happened, a secondary text can be added. In this case, the primary message entered when creating the message dialog is made bigger and set to bold text. The secondary message can be set by calling Gtk.MessageDialog.format_secondary_text().

17.2.1. MessageDialog Objects

class Gtk.MessageDialog([parent[, flags[, message_type[, buttons, [message_format]]]])

Creates a new Gtk.MessageDialog with transient parent parent. The flags argument can be used to make the dialog model (Gtk.DialogFlags.MODAL) and/or to have it destroyed along with its transient parent (Gtk.DialogFlags.DESTROY_WITH_PARENT).

message_type can be set to one of the following values:

  • Gtk.MessageType.INFO: Informational message
  • Gtk.MessageType.WARNING: Non-fatal warning message
  • Gtk.MessageType.QUESTION: Question requiring a choice
  • Gtk.MessageType.ERROR: Fatal error message
  • Gtk.MessageType.OTHER: None of the above, doesn’t get an icon

It is also possible to set a variety of buttons on the message dialog, to retrieve different responses from the user. One of the following values can be used:

  • Gtk.ButtonsType.NONE: no buttons at all
  • Gtk.ButtonsType.OK: an OK button
  • Gtk.ButtonsType.CLOSE: a Close button
  • Gtk.ButtonsType.CANCEL: a Cancel button
  • Gtk.ButtonsType.YES_NO: Yes and No buttons
  • Gtk.ButtonsType.OK_CANCEL: OK and Cancel buttons

Finally, message_format is some text that the user may want to see.

All arguments are optional and can be referred to as key-word arguments as well.

format_secondary_text(message_format)

Sets the secondary text of the message dialog to be message_format.

Note that setting a secondary text makes the primary text (message_format argument of Gtk.MessageDialog constructor) become bold, unless you have provided explicit markup.

17.2.2. Example

_images/messagedialog_example.png
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
from gi.repository import Gtk

class MessageDialogWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="MessageDialog Example")

        box = Gtk.Box(spacing=6)
        self.add(box)

        button1 = Gtk.Button("Information")
        button1.connect("clicked", self.on_info_clicked)
        box.add(button1)

        button2 = Gtk.Button("Error")
        button2.connect("clicked", self.on_error_clicked)
        box.add(button2)

        button3 = Gtk.Button("Warning")
        button3.connect("clicked", self.on_warn_clicked)
        box.add(button3)

        button4 = Gtk.Button("Question")
        button4.connect("clicked", self.on_question_clicked)
        box.add(button4)

    def on_info_clicked(self, widget):
        dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.INFO,
            Gtk.ButtonsType.OK, "This is an INFO MessageDialog")
        dialog.format_secondary_text(
            "And this is the secondary text that explains things.")
        dialog.run()
        print "INFO dialog closed"

        dialog.destroy()

    def on_error_clicked(self, widget):
        dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.ERROR,
            Gtk.ButtonsType.CANCEL, "This is an ERROR MessageDialog")
        dialog.format_secondary_text(
            "And this is the secondary text that explains things.")
        dialog.run()
        print "ERROR dialog closed"

        dialog.destroy()

    def on_warn_clicked(self, widget):
        dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.WARNING,
            Gtk.ButtonsType.OK_CANCEL, "This is an WARNING MessageDialog")
        dialog.format_secondary_text(
            "And this is the secondary text that explains things.")
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print "WARN dialog closed by clicking OK button"
        elif response == Gtk.ResponseType.CANCEL:
            print "WARN dialog closed by clicking CANCEL button"

        dialog.destroy()

    def on_question_clicked(self, widget):
        dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.QUESTION,
            Gtk.ButtonsType.YES_NO, "This is an QUESTION MessageDialog")
        dialog.format_secondary_text(
            "And this is the secondary text that explains things.")
        response = dialog.run()
        if response == Gtk.ResponseType.YES:
            print "QUESTION dialog closed by clicking YES button"
        elif response == Gtk.ResponseType.NO:
            print "QUESTION dialog closed by clicking NO button"

        dialog.destroy()

win = MessageDialogWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

17.3. FileChooserDialog

The Gtk.FileChooserDialog is suitable for use with “File/Open” or “File/Save” menu items. You can use all of the Gtk.FileChooser methods on the file chooser dialog as well as those for Gtk.Dialog.

When creating a Gtk.FileChooserDialog you have to define the dialog’s purpose:

  • To select a file for opening, as for a File/Open command, use Gtk.FileChooserAction.OPEN
  • To save a file for the first time, as for a File/Save command, use Gtk.FileChooserAction.SAVE, and suggest a name such as “Untitled” with Gtk.FileChooser.set_current_name().
  • To save a file under a different name, as for a File/Save As command, use Gtk.FileChooserAction.SAVE, and set the existing filename with Gtk.FileChooser.set_filename().
  • To choose a folder instead of a file, use Gtk.FileChooserAction.SELECT_FOLDER.

Gtk.FileChooserDialog inherits from Gtk.Dialog, so buttons have response IDs such as Gtk.ResponseType.ACCEPT and Gtk.ResponseType.CANCEL which can be specified in the Gtk.FileChooserDialog constructor. In contrast to Gtk.Dialog, you can not use custom response codes with Gtk.FileChooserDialog. It expects that at least one button will have of the following response IDs:

  • Gtk.ResponseType.ACCEPT
  • Gtk.ResponseType.OK
  • Gtk.ResponseType.YES
  • Gtk.ResponseType.APPLY

When the user is finished selecting files, your program can get the selected names either as filenames (Gtk.FileChooser.get_filename()) or as URIs (Gtk.FileChooser.get_uri()).

By default, Gtk.FileChooser only allows a single file to be selected at a time. To enable multiple files to be selected, use Gtk.FileChooser.set_select_multiple(). Retrieving a list of selected files is possible with either Gtk.FileChooser.get_filenames() or Gtk.FileChooser.get_uris().

Gtk.FileChooser also supports a variety of options which make the files and folders more configurable and accessible.

Furthermore, you can specify which kind of files are displayed by creating Gtk.FileFilter objects and calling Gtk.FileChooser.add_filter(). The user can then select one of the added filters from a combo box at the bottom of the file chooser.

17.3.1. FileChooser Objects

class Gtk.FileChooserDialog([title[, parent[, action[, buttons]]])

Creates a new Gtk.FileChooserDialog with title title and transient parent *parent.

action can be one of the following:

  • Gtk.FileChooserAction.OPEN: The file chooser will only let the user pick an existing file.
  • Gtk.FileChooserAction.SAVE: The file chooser will let the user pick an existing file, or type in a new filename.
  • Gtk.FileChooserAction.SELECT_FOLDER: The file chooser will let the user pick an existing folder.
  • Gtk.FileChooserAction.CREATE_FOLDER: The file chooser will let the user name an existing or new folder.

The buttons argument has the same format as for the Gtk.Dialog constructor.

class Gtk.FileChooser
set_current_name(name)

Sets the current name in the file selector, as if entered by the user.

set_filename(filename)

Sets filename as the current filename for the file chooser, by changing to the file’s parent folder and actually selecting the file in list; all other files will be unselected. If the chooser is in Gtk.FileChooserAction.SAVE mode, the file’s base name will also appear in the dialog’s file name entry.

Note that the file must exist, or nothing will be done except for the directory change.

set_select_multiple(select_multiple)

Sets whether multiple files can be selected. This is only relevant if the mode is Gtk.FileChooserAction.OPEN or Gtk.FileChooserAction.SELECT_FOLDER.

set_local_only(local_only)

Sets whether only local files can be selected.

set_show_hidden(show_hidden)

Sets whether to display hidden files and folders.

set_do_overwrite_confirmation(do_overwrite_confirmation)

Sets whether to confirm overwriting in save mode.

get_filename()

Returns the filename for the currently selected file in the file selector. If multiple files are selected, use get_filenames() instead.

get_filenames()

Returns a list of all the selected files and subfolders in the current folder. The returned names are full absolute paths. If files in the current folder cannot be represented as local filenames they will be ignored. Use get_uris() instead.

get_uri()

Returns the URI for the currently selected file in the file selector. If multiple files are selected, use get_uris() instead.

get_uris()

Returns a list of all the selected files and subfolders in the current folder. The returned names are full absolute URIs.

add_filter(filter)

Adds the Gtk.FileFilter instance filter to the list of filters that the user can choose from. When a filter is selected, only files that are passed by that filter are displayed.

class Gtk.FileFilter
set_name(name)

Sets the human-readable name of the filter; this is the string that will be displayed in the file selector user interface if there is a selectable list of filters.

add_mime_type(mime_type)

Adds a rule allowing a given mime type to filter.

add_pattern(pattern)

Adds a rule allowing a shell style glob to a filter.

17.3.2. Example

_images/filechooserdialog_example.png
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from gi.repository import Gtk

class FileChooserWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="FileChooser Example")

        box = Gtk.Box(spacing=6)
        self.add(box)

        button1 = Gtk.Button("Choose File")
        button1.connect("clicked", self.on_file_clicked)
        box.add(button1)

        button2 = Gtk.Button("Choose Folder")
        button2.connect("clicked", self.on_folder_clicked)
        box.add(button2)

    def on_file_clicked(self, widget):
        dialog = Gtk.FileChooserDialog("Please choose a file", self,
            Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             Gtk.STOCK_OPEN, Gtk.ResponseType.OK))

        self.add_filters(dialog)

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print "Open clicked"
            print "File selected: " + dialog.get_filename()
        elif response == Gtk.ResponseType.CANCEL:
            print "Cancel clicked"

        dialog.destroy()

    def add_filters(self, dialog):
        filter_text = Gtk.FileFilter()
        filter_text.set_name("Text files")
        filter_text.add_mime_type("text/plain")
        dialog.add_filter(filter_text)

        filter_py = Gtk.FileFilter()
        filter_py.set_name("Python files")
        filter_py.add_mime_type("text/x-python")
        dialog.add_filter(filter_py)

        filter_any = Gtk.FileFilter()
        filter_any.set_name("Any files")
        filter_any.add_pattern("*")
        dialog.add_filter(filter_any)

    def on_folder_clicked(self, widget):
        dialog = Gtk.FileChooserDialog("Please choose a folder", self,
            Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
             "Select", Gtk.ResponseType.OK))
        dialog.set_default_size(800, 400)

        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print "Select clicked"
            print "Folder selected: " + dialog.get_filename()
        elif response == Gtk.ResponseType.CANCEL:
            print "Cancel clicked"

        dialog.destroy()

win = FileChooserWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

Project Versions

Table Of Contents

Previous topic

16. Menus

Next topic

18. Clipboard

This Page