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.
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.
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);
}
}
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);
}
}
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);
}
}
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í.
#!/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);
#!/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);