Home > Gtk3, PyGObject, python > PyGObject: Gtk.MessageDialog

PyGObject: Gtk.MessageDialog

13 Aprile 2020

torna all’indice degli appunti

MessageDialog

Il widget Gtk.MessageDialog è un widget che visualizza una finestra di dialog con un testo e
all’occorrenza dei bottoni di scelta.
La differenza tra Gtk.MessageDialog e Gtk.Dialog è che nel primo, viene settata a True la property
“skip-taskbar-hint”, che permette di nascondere il dialog all task-bar.
Il metodo migliore per utilizzare un dialog, è chiamarne il metodo run() che rende il dialog
modal.
In sostanza modal significa che il dialog diventa automaticamente figlio della top-level window
principale dalla quale lo abbiamo generato e attende fino a che l’utente non interagisce con esso
(es. cliccando un Button), per poi tornare alla window parent che l’ha generato.

Per creare un message dialog si utilizza il costruttore Gtk.MessageDialog(*args, **kwargs).

Le properties principali dell’oggetto MessageDialog sono:

Name Type Flags Short Description
buttons Gtk.ButtonsType w/co I bottoni (Gtk.ButtonsType) visualizzati nel dialog
message-area Gtk.Widget r il widget Gtk.Box che gestisce le labels primaria e secondaria
message-type Gtk.MessageType r/w/c/en l’oggetto Gtk.MessageType che definisce il tipo di oggetto
secondary-text str r/w il messaggio secondario del dialog
secondary-use-markup bool r/w/en il boolean che, settato a True, permette di includere il Pango markup
text str r/w il testo principale del dialog
use-markup bool r/w/en il boolean che, settato a True, permette di includere il Pango markup
 
>>> import gi
>>> gi.require_version('Gtk', '3.0')
>>> from gi.repository import Gtk, GLib, Gdk
>>> dialog = Gtk.MessageDialog(parent=None, use_markup=False, message_type=Gtk.MessageType.INFO,
...                            buttons=Gtk.ButtonsType.OK, text="This is an INFO message dialog")

E’ possibile passare i parametri del widget in fase di costruzione, ma è possibile accedervi e
modificarli anche in seguito, utilizzando i metodi getter e setter get_property(property_name)
e set_property(property_name, property_value):
A differenza di altri widget, però, le properties leggibili, sono limitate, poichè i flags settati
per queste, non permettono la lettura/scrittura:

 
>>> for p in dialog.props:
...     if p.flags == 227:
...         print(p)        
...         
<GParamString 'name'>
<GParamObject 'parent'>
<GParamBoolean 'is-focus'>
<GParamString 'tooltip-markup'>
<GParamString 'tooltip-text'>
<GParamInt 'margin'>
<GParamBoolean 'expand'>
<GParamString 'title'>
<GParamString 'role'>
<GParamString 'text'>
<GParamString 'secondary-text'>
>>> dialog.get_property("text")
'This is an INFO message dialog'

oppure con i metodi getter e setter specifici get_() e set_(value):

 
>>> dialog.set_tooltip_text("Tooltip text")
>>> dialog.get_tooltip_text()
'Tooltip text'

Quindi è bene settare le properties non accessibili, in fase di costruzione!

Metodi

Di seguito i metodi utilizzabili con il widget Gtk.MessageDialog:

format_secondary_markup(message_format)

Setta il testo secondario del message dialog che verrà formattato con il Pango text markup language.
Questa funzione non esegue l’escape di caratteri XML speciali.
Parametri:
message_format: la stringa in formato markup;

format_secondary_text(message_format)

Setta il testo secondario del message dialog.
Parametri:
message_format: la stringa in formato markup;

get_message_area()

Ritorna un oggetto Gtk.Box corrispondente all’area dedicata dal message dialog, al testo

set_markup(str)

Setta il testo principale del message dialog che verrà formattato con il Pango text markup language.
Parametri:
str: la stringa in formato markup;

Tipi di MessageDialog

I tipi di MessageDialog sono definiti dall’Enum message_type che passiamo in fase di costruzione.
Questo Enum è di tipo Gtk.MessageType e può
assumere i seguenti valori:

INFO (0): Messaggio informativo semplice, di solito corredato da un Button OK.
WARNING (1): Messaggio di avviso;
QUESTION (2): Messaggio di scelta, con bottoni YES/NO;
ERROR (3): Messaggio di errore;
OTHER (4): Nessuna delle precedenti. E’ un messaggio personalizzabile;

Image

Settare un’immagine nel message dialog è molto semplice e ci sono più modi.
Creiamo un oggetto Gtk.Image con il classmethod Gtk.Image.new_from_file,
lo rendiamo visibile con il metodo show() e lo settiamo in fase di costruzione
dell’oggetto Gtk.MessageDialog con la property “image”.

Di seguito un codice d’esempio:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk


class GWindow(Gtk.Window):

    def __init__(self):
        super().__init__(title="MessageDialog Example")

        button1 = Gtk.Button(label="Information")
        button2 = Gtk.Button(label="Error")
        button3 = Gtk.Button(label="Warning")
        button4 = Gtk.Button(label="Question")
        # Bindings
        button1.connect("clicked", self.on_info_clicked)
        button2.connect("clicked", self.on_error_clicked)
        button4.connect("clicked", self.on_question_clicked)
        button3.connect("clicked", self.on_warning_clicked)
        # Layout
        box = Gtk.Box(spacing=6)
        box.add(button1)
        box.add(button2)
        box.add(button3)
        box.add(button4)
        self.add(box)

    def on_info_clicked(self, widget):
        image = Gtk.Image.new_from_file("info.png")
        image.show()
        dialog = Gtk.MessageDialog(parent=self, use_markup=False, title="Info",
                                   message_type=Gtk.MessageType.INFO,
                                   buttons=Gtk.ButtonsType.OK, image=image,
                                   text="Primary Message Text")
        dialog.format_secondary_text("secondary text that explains things")
        dialog.run()  # Return when user click dialog buttons
        dialog.destroy()

    def on_error_clicked(self, widget):
        image = Gtk.Image.new_from_file("error.png")
        image.show()
        dialog = Gtk.MessageDialog(parent=self, use_markup=True, title="Error",
                                   message_type=Gtk.MessageType.ERROR,
                                   buttons=Gtk.ButtonsType.CANCEL, image=image,
                                   text='<span foreground="red" weight="bold">'
                                        'Primary Error Message Text</span>')
        dialog.format_secondary_text("secondary text that explains things")
        dialog.run()
        dialog.destroy()

    def on_warning_clicked(self, widget):
        image = Gtk.Image.new_from_file("warning.png")
        image.show()
        dialog = Gtk.MessageDialog(parent=self, use_markup=True, 
                                   title="Warning", image=image,
                                   message_type=Gtk.MessageType.WARNING,
                                   buttons=Gtk.ButtonsType.OK_CANCEL, 
                                   text='<span foreground="blue" weight="bold">'
                                        'Primary Warning Message Text</span>')
        dialog.format_secondary_text("secondary text that explains things")
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print("WARNING: dialog closed by clicking OK button")
        elif response == Gtk.ResponseType.CANCEL:
            print("WARNING: dialog closed by clicking CANCEL button")
        dialog.destroy()

    def on_question_clicked(self, widget):
        image = Gtk.Image.new_from_file("question.png")
        image.show()
        dialog = Gtk.MessageDialog(parent=self, use_markup=False,
                                   title="Question", 
                                   message_type=Gtk.MessageType.QUESTION,
                                   buttons=Gtk.ButtonsType.YES_NO,
                                   text="This is an QUESTION MessageDialog")
        dialog.format_secondary_text("secondary text that explains things")
        response = dialog.run()
        if response == Gtk.ResponseType.YES:
            print("INFO: dialog closed by clicking YES button")
        elif response == Gtk.ResponseType.NO:
            print("INFO: dialog closed by clicking NO button")
        dialog.destroy()


if __name__ == "__main__":
    win = GWindow()
    win.connect("destroy", Gtk.main_quit)
    win.show_all()
    Gtk.main()

Custom Dialog

Se nessuno dei dialogs disponibili soddisfa le nostre esigenze, possiamo sempre crearne uno
personalizzato utilizzando la classe Gtk.Dialog.
Ad esempio vogliamo inserire all’interno una entry per digitare un valore e recuperarlo, vogliamo
mettere una o più labels e l’icona preferita…

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk


class CustomDialog(Gtk.Dialog):
    def __init__(self, parent):
        super().__init__(title="Custom Dialog", parent=parent)
        self.result = None
        self.add_buttons(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                         Gtk.STOCK_OK, Gtk.ResponseType.OK)
        self.set_default_size(250, 100)
        image = Gtk.Image.new_from_file("warning.png")
        image.show()
        label = Gtk.Label(label="Enter new value")
        self.entry = Gtk.Entry()
        box = self.get_content_area()
        box.set_spacing(15)
        box.add(image)
        box.add(label)
        box.add(self.entry)
        self.show_all()
        # bindings
        self.connect("response", self.on_response)  # get the entry value

    def on_response(self, widget, response_id):
        self.result = self.entry.get_text()

    def get_result(self):
        return self.result


class GWindow(Gtk.Window):
    def __init__(self):
        super().__init__(title="Custom Dialog Example")
        self.set_border_width(6)
        button = Gtk.Button(label="Open dialog")
        button.connect("clicked", self.on_button_clicked)
        self.add(button)

    def on_button_clicked(self, widget):
        dialog = CustomDialog(parent=self)
        response = dialog.run()
        if response == Gtk.ResponseType.OK:
            print("INFO: The OK button was clicked with result %s" %
                  dialog.get_result())
        elif response == Gtk.ResponseType.CANCEL:
            print("INFO: The Cancel button was clicked")
        dialog.destroy()


if __name__ == "__main__":
    win = GWindow()
    win.connect("destroy", Gtk.main_quit)
    win.show_all()
    Gtk.main()

Nota:
connettere il dialog al segnale response, ci permettere di assegnare il valore della entry nella
nostra variabile, che poi possiamo recuperare all’occorrenza con il getter.

link di riferimento:

torna all’indice degli appunti
Gtk3 MessageDialog

Categorie:Gtk3, PyGObject, python Tag: , ,
I commenti sono chiusi.