Taryn Fox jewelfox@fursona.net 2012 Crear botones y otros widgets que efectúan acciones cuando los pulsa. Daniel Mustieles daniel.mustieles@gmail.com 2011 - 2017 Nicolás Satragno nsatragno@gmail.com 2012 - 2013 Jorge González jorgegonz@svn.gnome.org 2011 3. Obtener la señal

En el último tutorial, aprendió cómo crear widgets como etiquetas, imágenes y botones. Aquí, aprenderá cómo hacer que los botones y otros widgets de entrada hagan cosas realmente, escribiendo funciones que manejen las señales que envían cuando se pulsan o interactúan.

Una aplicación básica

En GNOME, los widgets con los que puede interactuar, como los botones y los interruptores, envían señales cuando se pulsan o activan. Un botón, por ejemplo, envía la señal «clicked» cuando alguien lo pulsa. Cuando esto sucede, GNOME busca la parte de su código que dice qué hacer.

¿Cómo se escribe ese código? Conectando la señal «clicked» del botón a una función de retorno de llamada, que es una función que se escribe sólo para manejar esa señal. Entonces, cuando se envía esa señal, la función conectada se ejecuta.

Aquí hay un ejemplo extremadamente básico:

La ApplicationWindow tiene un botón y una etiqueta dentro, ordenados en una rejilla. Cuando se pulsa el botón, una variable que guarda el número de galletas se incrementa en 1, y la etiqueta que muestra cuántas galletas hay se actualiza.

Las galletas en este ejemplo no son las «cookies» que obtiene de sitios web, que almacenan su información de sesión y pueden rastrear qué sitios visitó. Son solamente utilería imaginaria. Puede hornear algunas reales, si quiere.

Aquí está el código básico y repetitivo que va al inicio de la aplicación, antes de comenzar a crear la ventana y los widgets. Además de que la aplicación tiene un nombre único, el cambio más grande respecto del código usual es que se crea una variable global cerca del principio, para guardar el número de galletas.

#!/usr/bin/gjs imports.gi.versions.Gtk = '3.0'; const Gtk = imports.gi.Gtk; // We start out with 0 cookies var cookies = 0; class GettingTheSignal { // Create the application itself constructor() { this.application = new Gtk.Application(); // Connect 'activate' and 'startup' signals to the callback functions this.application.connect('activate', this._onActivate.bind(this)); this.application.connect('startup', this._onStartup.bind(this)); } // Callback function for 'activate' signal presents window when active _onActivate() { this._window.present(); } // Callback function for 'startup' signal builds the UI _onStartup() { this._buildUI (); }

Eche un vistazo a la parte que usa el método «connect» de la aplicación y «bind», para conectar sus señales «activate» y «startup» a las funciones que presentan la ventana y construyen la IU. Va a hacer lo mismo con el botón cuando llegue a él, excepto que conectará la señal «clicked» en su lugar.

Pulsar el botón

Como siempre, se pondrá todo el código para crear el botón y los otros widgets dentro de la función «_buildUI», que se llama cuando la aplicación arranca.

// Build the application's UI _buildUI() {

Primero, se crea la ventana en sí:

// Create the application window this._window = new Gtk.ApplicationWindow({ application: this.application, window_position: Gtk.WindowPosition.CENTER, default_height: 200, default_width: 400, title: "Click the button to get a cookie!"});

Tenga en cuenta que se han establecido sus propiedades «default_height» y «default_width». Estas le permiten controlar qué tan alta y ancha será la «ApplicationWindow», en píxeles.

A continuación, se creará la etiqueta que muestra el número de galletas. Se puede usar la variable de las galletas como parte de la propiedad «label» de la etiqueta.

// Create the label this._cookieLabel = new Gtk.Label ({ label: "Number of cookies: " + cookies });

Ahora se creará el botón. Se configura su propiedad «label» para que muestre el texto que quiere en el botón, y se conecta su señal «clicked» a una función llamada «_getACookie», que se escribirá después de haber construido la IU de la aplicación.

// Create the cookie button this._cookieButton = new Gtk.Button ({ label: "Get a cookie" }); // Connect the cookie button to the function that handles clicking it this._cookieButton.connect ('clicked', this._getACookie.bind(this));

Finalmente, se crea una rejilla, se le adjuntan la etiqueta y el botón, se añade a la ventana y se le dice que se muestre con su contenido. Eso es todo lo que necesita dentro de la función «_buildUI», por lo que se cierra con un paréntesis y un punto y coma que le dice a GNOME que continúe con la siguiente función. Tenga en cuenta que incluso a pesar de que se escribió el código de la etiqueta primero, igual se puede adjuntar a la rejilla de forma tal que quede en la parte inferior.

// Create a grid to arrange everything inside this._grid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER, row_spacing: 20 }); // Put everything inside the grid this._grid.attach (this._cookieButton, 0, 0, 1, 1); this._grid.attach (this._cookieLabel, 0, 1, 1, 1); // Add the grid to the window this._window.add (this._grid); // Show the window and all child widgets this._window.show_all(); }

Ahora, se escribe la función «_getACookie». Cada vez que el botón envíe su señal «clicked», se ejecutará el código de esta función. En este caso, todo lo que hace es incrementar el número de galletas en 1, y actualizar la etiqueta para que muestre el número nuevo. Esto se hace usando el método «set_label» de la etiqueta.

Muchos widgets tienen las mismas propiedades y métodos. Tanto las etiquetas como los botones, por ejemplo, tienen una propiedad «label» que dice qué texto va dentro de ellos, y métodos «get_label» y «set_label» que le permiten verificar cuál es el texto y cambiarlo, respectivamente. Por lo que si aprende cómo funciona un widget, también aprenderá cómo funcionan otros similares.

_getACookie: function() { // Increase the number of cookies by 1 and update the label cookies++; this._cookieLabel.set_label ("Number of cookies: " + cookies); } };

Finalmente, se ejecuta la aplicación, usando el mismo tipo de código que en el tutorial anterior.

// Run the application let app = new GettingTheSignal (); app.application.run (ARGV);
Pulsar el interruptor

Los botones no son el único widget de entrada de la caja de herramientas de GTK+. También se pueden usar interruptores, como el de este ejemplo. Los interruptores no tienen una propiedad «label», por lo que hay que crear una etiqueta separada que diga qué hace a su lado.

Un interruptor tiene dos posiciones, «apagado» y «encendido». Cuando un interruptor está encendido, su texto y color de fondo cambian, indicando en qué posición está.

Puede haber visto interruptores como estos en el menú de accesibilidad de GNOME, que le permiten conmutar características como texto grande y el teclado en pantalla. En este caso, el interruptor controla un dispensador de galletas imaginario. Si el interruptor está encendido, puede obtener galletas pulsando el botón «Get a cookie». Si está apagado, pulsar el botón no hará nada.

Puede llegar al menú de accesibilidad pulsando el contorno de un humano, cerca de su nombre en la esquina superior derecha de la pantalla.

Aquí se muestra cómo crear el interruptor:

// Create the switch that controls whether or not you can win this._cookieSwitch = new Gtk.Switch ();

En realidad no se necesita conectar el interruptor a nada. Todo lo que hay que hacer es escribir una declaración «if» en la función «_getACookie», para verificar si el interruptor está encendido. Si quisiera hacer que algo suceda tan pronto como se acciona el interruptor, conectaría su señal «notify::active», así:

// Connect the switch to the function that handles it this._cookieSwitch.connect ('notify::active', this._cookieDispenser.bind(this));

De manera predeterminada, un interruptor está apagado. Si quisiera que el interruptor arrancara encendido, establecería el valor de su propiedad «active» a «true» cuando lo crea.

this._cookieSwitch = new Gtk.Switch ({ active: true });

Por ahora sólo se creará normalmente, y después se creará la etiqueta que lo acompaña. Se quiere que el interruptor y la etiqueta estén lado a lado, por lo que se creará una rejilla sólo para ellos, y después se pondrá esa rejilla en la rejilla más grande que contiene todos los widgets. Aquí está cómo se ve el código para crear todo eso:

// Create the switch that controls whether or not you can win this._cookieSwitch = new Gtk.Switch (); // Create the label to go with the switch this._switchLabel = new Gtk.Label ({ label: "Cookie dispenser" }); // Create a grid for the switch and its label this._switchGrid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER }); // Put the switch and its label inside that grid this._switchGrid.attach (this._switchLabel, 0, 0, 1, 1); this._switchGrid.attach (this._cookieSwitch, 1, 0, 1, 1);

Y ahora se organiza todo en la rejilla más grande así.

// Put everything inside the grid this._grid.attach (this._cookieButton, 0, 0, 1, 1); this._grid.attach (this._switchGrid, 0, 1, 1, 1); this._grid.attach (this._cookieLabel, 0, 2, 1, 1);

Ahora se cambia la función «_getACookie» para que verifique si el dispensador de galletas está encendido. Se hace usando el método «get_active» del interruptor. Devuelve «true» si está encendido, y «false» si está apagado.

Cuando un método se usa en una declaración «if» como esta, el código dentro de la declaración «if» se ejecuta si el método devuelve «true».

_getACookie() { // Is the cookie dispenser turned on? if (this._cookieSwitch.get_active()) { // Increase the number of cookies by 1 and update the label cookies++; this._cookieLabel.set_label ("Number of cookies: " + cookies); } }
Sintonizar la radio

Otro tipo de widget de entrada que puede usar se llama botón de radio. Se crean en grupos, y sólo un botón de radio en un grupo puede seleccionarse por vez. Se llaman botones de radio porque funcionan como los botones de selección de canal en las radios de coches viejos. La radio sólo podía sintonizarse con una estación a la vez, por lo que cada vez que presionaba un botón, otro saltaba hacia arriba.

Primero, cambie el nombre de la «ApplicationWindow» e incremente su propiedad «border_width», para que los widgets no se empaqueten demasiado apretados. El «border_width» es el número de píxeles entre cualquier widget y el borde de la ventana.

// Create the application window this._window = new Gtk.ApplicationWindow({ application: this.application, window_position: Gtk.WindowPosition.CENTER, default_height: 200, default_width: 400, border_width: 20, title: "Choose the one that says 'cookie'!"});

Después de eso, se crean los botones de radio. ¿Recuerda cómo se crean en grupos? Eso se hace estableciendo la propiedad «group» de cada botón de radio al nombre de otro.

// Create the radio buttons this._cookieRadio = new Gtk.RadioButton ({ label: "Cookie" }); this._notCookieOne = new Gtk.RadioButton ({ label: "Not cookie", group: this._cookieRadio }); this._notCookieTwo = new Gtk.RadioButton ({ label: "Not cookie", group: this._cookieRadio });

A continuación, se crea una rejilla para los botones de radio. Recuerde, no es necesario ordenar cosas en rejillas en el mismo orden que se crean.

// Arrange the radio buttons in their own grid this._radioGrid = new Gtk.Grid (); this._radioGrid.attach (this._notCookieOne, 0, 0, 1, 1); this._radioGrid.attach (this._cookieRadio, 0, 1, 1, 1); this._radioGrid.attach (this._notCookieTwo, 0, 2, 1, 1);

Normalmente, el botón de radio que está seleccionado de manera predeterminada es el del nombre del grupo. Sin embargo, se quiere que el primer botón «Not cookie» esté seleccionado de manera predeterminada, por lo que se usa su método «set_active».

También se podría establecer su propiedad «active» a «true» cuando se crea.

// Set the button that will be at the top to be active by default this._notCookieOne.set_active (true);

Ahora se organiza todo en la rejilla principal como siempre…

// Put everything inside the grid this._grid.attach (this._radioGrid, 0, 0, 1, 1); this._grid.attach (this._cookieButton, 0, 1, 1, 1); this._grid.attach (this._cookieLabel, 0, 2, 1, 1);

Y después se cambia la función «_getACookie» para probar si el botón de la galleta es el que está seleccionado.

_getACookie() { // Did you select "cookie" instead of "not cookie"? if (this._cookieRadio.get_active()) { // Increase the number of cookies by 1 and update the label cookies++; this._cookieLabel.set_label ("Number of cookies: " + cookies); } }
¿Puede deletrear «cookie»?

El último widget de entrada que se va a cubrir es el widget «Entry», que se usa para entrada de texto de una sola línea.

Si necesita poder introducir un párrafo entero o más, como si estuviera construyendo un editor de texto, querrá echar un vistazo al widget TextView, mucho más configurable.

Después de cambiar el nombre de la ventana, se crea el widget «Entry».

// Create the text entry field this._spellCookie = new Gtk.Entry ();

A continuación, se organiza todo en la rejilla…

// Put everything inside the grid this._grid.attach (this._spellCookie, 0, 0, 1, 1); this._grid.attach (this._cookieButton, 0, 1, 1, 1); this._grid.attach (this._cookieLabel, 0, 2, 1, 1);

Y ahora se modifica la declaración «if» de «_getACookie» nuevamente, usando el método «get_text» del «Entry» para obtener el texto que introdujo y verificar si deletreó «cookie» correctamente. No importa si utiliza mayúsculas, por lo que se usa el método «toLowerCase» integrado de JavaScript para cambiar todo el texto del «Entry» a minúsculas dentro de la declaración «if».

Un widget «Entry» no tiene una propiedad «label», que es una cadena de texto establecida que el usuario no puede cambiar (normalmente no puede cambiar la etiqueta de un botón, por ejemplo). En su lugar, tiene una propiedad «text», que cambia de acuerdo a lo que el usuario introduce.

_getACookie() { // Did you spell "cookie" correctly? if ((this._spellCookie.get_text()).toLowerCase() == "cookie") { // Increase the number of cookies by 1 and update the label cookies++; this._cookieLabel.set_label ("Number of cookies: " + cookies); } }
¿Qué viene ahora?

Siga leyendo, si quiere ver el código completo para cada versión de la aplicación creadora de galletas.

La página principal de tutoriales de JavaScript tiene ejemplos de código más detallados para cada widget de entrada, incluyendo varios no cubiertos aquí.

Ejemplos de código completos
Ejemplo de código con botón #!/usr/bin/gjs imports.gi.versions.Gtk = '3.0'; const Gtk = imports.gi.Gtk; // We start out with 0 cookies var cookies = 0; class GettingTheSignal { // Create the application itself constructor() { this.application = new Gtk.Application(); // Connect 'activate' and 'startup' signals to the callback functions this.application.connect('activate', this._onActivate.bind(this)); this.application.connect('startup', this._onStartup.bind(this)); } // Callback function for 'activate' signal presents window when active _onActivate() { this._window.present(); } // Callback function for 'startup' signal builds the UI _onStartup() { this._buildUI(); } // Build the application's UI _buildUI() { // Create the application window this._window = new Gtk.ApplicationWindow({ application: this.application, window_position: Gtk.WindowPosition.CENTER, default_height: 200, default_width: 400, title: "Click the button to get a cookie!"}); // Create the label this._cookieLabel = new Gtk.Label ({ label: "Number of cookies: " + cookies }); // Create the cookie button this._cookieButton = new Gtk.Button ({ label: "Get a cookie" }); // Connect the cookie button to the function that handles clicking it this._cookieButton.connect ('clicked', this._getACookie.bind(this)); // Create a grid to arrange everything inside this._grid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER, row_spacing: 20 }); // Put everything inside the grid this._grid.attach (this._cookieButton, 0, 0, 1, 1); this._grid.attach (this._cookieLabel, 0, 1, 1, 1); // Add the grid to the window this._window.add (this._grid); // Show the window and all child widgets this._window.show_all(); } _getACookie() { // Increase the number of cookies by 1 and update the label cookies++; this._cookieLabel.set_label ("Number of cookies: " + cookies); } }; // Run the application let app = new GettingTheSignal (); app.application.run (ARGV);
Ejemplo de código con interruptor #!/usr/bin/gjs imports.gi.versions.Gtk = '3.0'; const Gtk = imports.gi.Gtk; // We start out with 0 cookies var cookies = 0; class GettingTheSignal { // Create the application itself constructor() { this.application = new Gtk.Application(); // Connect 'activate' and 'startup' signals to the callback functions this.application.connect('activate', this._onActivate.bind(this)); this.application.connect('startup', this._onStartup.bind(this)); } // Callback function for 'activate' signal presents window when active _onActivate() { this._window.present(); } // Callback function for 'startup' signal builds the UI _onStartup() { this._buildUI(); } // Build the application's UI _buildUI() { // Create the application window this._window = new Gtk.ApplicationWindow({ application: this.application, window_position: Gtk.WindowPosition.CENTER, default_height: 200, default_width: 400, title: "Click the button to get a cookie!"}); // Create the label this._cookieLabel = new Gtk.Label ({ label: "Number of cookies: " + cookies }); // Create the cookie button this._cookieButton = new Gtk.Button ({ label: "Get a cookie" }); // Connect the cookie button to the function that handles clicking it this._cookieButton.connect ('clicked', this._getACookie.bind(this)); // Create the switch that controls whether or not you can win this._cookieSwitch = new Gtk.Switch (); // Create the label to go with the switch this._switchLabel = new Gtk.Label ({ label: "Cookie dispenser" }); // Create a grid for the switch and its label this._switchGrid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER }); // Put the switch and its label inside that grid this._switchGrid.attach (this._switchLabel, 0, 0, 1, 1); this._switchGrid.attach (this._cookieSwitch, 1, 0, 1, 1); // Create a grid to arrange everything else inside this._grid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER, row_spacing: 20 }); // Put everything inside the grid this._grid.attach (this._cookieButton, 0, 0, 1, 1); this._grid.attach (this._switchGrid, 0, 1, 1, 1); this._grid.attach (this._cookieLabel, 0, 2, 1, 1); // Add the grid to the window this._window.add (this._grid); // Show the window and all child widgets this._window.show_all(); } _getACookie() { // Is the cookie dispenser turned on? if (this._cookieSwitch.get_active()) { // Increase the number of cookies by 1 and update the label cookies++; this._cookieLabel.set_label ("Number of cookies: " + cookies); } } }; // Run the application let app = new GettingTheSignal (); app.application.run (ARGV);
Ejemplo de código con botón de radio #!/usr/bin/gjs imports.gi.versions.Gtk = '3.0'; const Gtk = imports.gi.Gtk; // We start out with 0 cookies var cookies = 0; class GettingTheSignal { // Create the application itself constructor() { this.application = new Gtk.Application(); // Connect 'activate' and 'startup' signals to the callback functions this.application.connect('activate', this._onActivate.bind(this)); this.application.connect('startup', this._onStartup.bind(this)); } // Callback function for 'activate' signal presents window when active _onActivate() { this._window.present(); } // Callback function for 'startup' signal builds the UI _onStartup() { this._buildUI(); } // Build the application's UI _buildUI() { // Create the application window this._window = new Gtk.ApplicationWindow({ application: this.application, window_position: Gtk.WindowPosition.CENTER, default_height: 200, default_width: 400, border_width: 20, title: "Choose the one that says 'cookie'!"}); // Create the radio buttons this._cookieRadio = new Gtk.RadioButton ({ label: "Cookie" }); this._notCookieOne = new Gtk.RadioButton ({ label: "Not cookie", group: this._cookieRadio }); this._notCookieTwo = new Gtk.RadioButton ({ label: "Not cookie", group: this._cookieRadio }); // Arrange the radio buttons in their own grid this._radioGrid = new Gtk.Grid (); this._radioGrid.attach (this._notCookieOne, 0, 0, 1, 1); this._radioGrid.attach (this._cookieRadio, 0, 1, 1, 1); this._radioGrid.attach (this._notCookieTwo, 0, 2, 1, 1); // Set the button that will be at the top to be active by default this._notCookieOne.set_active (true); // Create the cookie button this._cookieButton = new Gtk.Button ({ label: "Get a cookie" }); // Connect the cookie button to the function that handles clicking it this._cookieButton.connect ('clicked', this._getACookie.bind(this)); // Create the label this._cookieLabel = new Gtk.Label ({ label: "Number of cookies: " + cookies }); // Create a grid to arrange everything inside this._grid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER, row_spacing: 20 }); // Put everything inside the grid this._grid.attach (this._radioGrid, 0, 0, 1, 1); this._grid.attach (this._cookieButton, 0, 1, 1, 1); this._grid.attach (this._cookieLabel, 0, 2, 1, 1); // Add the grid to the window this._window.add (this._grid); // Show the window and all child widgets this._window.show_all(); } _getACookie() { // Did you select "cookie" instead of "not cookie"? if (this._cookieRadio.get_active()) { // Increase the number of cookies by 1 and update the label cookies++; this._cookieLabel.set_label ("Number of cookies: " + cookies); } } }; // Run the application let app = new GettingTheSignal (); app.application.run (ARGV);
Ejemplo de código con «Entry» #!/usr/bin/gjs imports.gi.versions.Gtk = '3.0'; const Gtk = imports.gi.Gtk; // We start out with 0 cookies var cookies = 0; class GettingTheSignal { // Create the application itself constructor() { this.application = new Gtk.Application(); // Connect 'activate' and 'startup' signals to the callback functions this.application.connect('activate', this._onActivate.bind(this)); this.application.connect('startup', this._onStartup.bind(this)); } // Callback function for 'activate' signal presents window when active _onActivate() { this._window.present(); } // Callback function for 'startup' signal builds the UI _onStartup() { this._buildUI(); } // Build the application's UI _buildUI() { // Create the application window this._window = new Gtk.ApplicationWindow({ application: this.application, window_position: Gtk.WindowPosition.CENTER, default_height: 200, default_width: 400, border_width: 20, title: "Spell 'cookie' to get a cookie!"}); // Create the text entry field this._spellCookie = new Gtk.Entry (); // Create the cookie button this._cookieButton = new Gtk.Button ({ label: "Get a cookie" }); // Connect the cookie button to the function that handles clicking it this._cookieButton.connect ('clicked', this._getACookie.bind(this)); // Create the label this._cookieLabel = new Gtk.Label ({ label: "Number of cookies: " + cookies }); // Create a grid to arrange everything inside this._grid = new Gtk.Grid ({ halign: Gtk.Align.CENTER, valign: Gtk.Align.CENTER, row_spacing: 20 }); // Put everything inside the grid this._grid.attach (this._spellCookie, 0, 0, 1, 1); this._grid.attach (this._cookieButton, 0, 1, 1, 1); this._grid.attach (this._cookieLabel, 0, 2, 1, 1); // Add the grid to the window this._window.add (this._grid); // Show the window and all child widgets this._window.show_all(); } _getACookie() { // Did you spell "cookie" correctly? if ((this._spellCookie.get_text()).toLowerCase() == "cookie") { // Increase the number of cookies by 1 and update the label cookies++; this._cookieLabel.set_label ("Number of cookies: " + cookies); } } }; // Run the application let app = new GettingTheSignal (); app.application.run (ARGV);