3.2. Un Hola Mundo Mejorado

    1   #!/usr/bin/env python
    2   
    3   # example helloworld2.py
    4   
    5   import gtk
    6   
    7   class HelloWorld2:
    8   
    9       # Our new improved callback.  The data passed to this method
   10       # is printed to stdout.
   11       def callback(self, widget, data):
   12           print "Hello again - %s was pressed" % data
   13   
   14       # another callback
   15       def delete_event(self, widget, event, data=None):
   16           gtk.main_quit()
   17           return gtk.FALSE
   18   
   19       def __init__(self):
   20           # Create a new window
   21           self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
   22   
   23           # This is a new call, which just sets the title of our
   24           # new window to "Hello Buttons!"
   25           self.window.set_title("Hello Buttons!")
   26   
   27           # Here we just set a handler for delete_event that immediately
   28           # exits GTK.
   29           self.window.connect("delete_event", self.delete_event)
   30   
   31           # Sets the border width of the window.
   32           self.window.set_border_width(10)
   33   
   34           # We create a box to pack widgets into.  This is described in detail
   35           # in the "packing" section. The box is not really visible, it
   36           # is just used as a tool to arrange widgets.
   37           self.box1 = gtk.HBox(gtk.FALSE, 0)
   38   
   39           # Put the box into the main window.
   40           self.window.add(self.box1)
   41   
   42           # Creates a new button with the label "Button 1".
   43           self.button1 = gtk.Button("Button 1")
   44   
   45           # Now when the button is clicked, we call the "callback" method
   46           # with a pointer to "button 1" as its argument
   47           self.button1.connect("clicked", self.callback, "button 1")
   48   
   49           # Instead of add(), we pack this button into the invisible
   50           # box, which has been packed into the window.
   51           self.box1.pack_start(self.button1, gtk.TRUE, gtk.TRUE, 0)
   52   
   53           # Always remember this step, this tells GTK that our preparation for
   54           # this button is complete, and it can now be displayed.
   55           self.button1.show()
   56   
   57           # Do these same steps again to create a second button
   58           self.button2 = gtk.Button("Button 2")
   59   
   60           # Call the same callback method with a different argument,
   61           # passing a pointer to "button 2" instead.
   62           self.button2.connect("clicked", self.callback, "button 2")
   63   
   64           self.box1.pack_start(self.button2, gtk.TRUE, gtk.TRUE, 0)
   65   
   66           # The order of showing the buttons is not really important, but I
   67           # recommend showing the window last, so it all pops up at once.
   68           self.button2.show()
   69           self.box1.show()
   70           self.window.show()
   71   
   72   def main():
   73       gtk.main()
   74   
   75   if __name__ == "__main__":
   76       hello = HelloWorld2()
   77       main()

Al ejecutar helloworld2.py se genera la ventana que se ve en la Figura 3.1. Ejemplo de Hola Mundo mejorado.

Figura 3.1. Ejemplo de Hola Mundo mejorado

Ejemplo de Hola Mundo mejorado

Esta vez verás que no hay una forma fácil de salir del programa, tienes que usar tu manejador de ventanas o la línea de comandos para matarlo. Un buen ejercicio para el lector sería insertar un tercer botón "Salir" que cerrara el programa. Puedes intentar jugar con las opciones de pack_start() mientras lees la siguiente sección. Prueba a cambiar de tamaño la ventana, y observa lo que pasa.

Sólo como una nota, hay otra constante útil para GtkWindow() - WINDOW_DIALOG. Esto interacciona con el manejador de ventanas de una forma un poco diferente y debe usarse para ventanas temporales.

A continuación se describen en orden las pequeñas diferencias en el código con respecto al primer programa helloworld.

Como ya se ha dicho no hay manejador para el evento "destroy" en la versión mejorada de helloworld.

Las líneas 11-12 definen un método de retrollamada que es similar a la retrollamada hello() en el primer helloworld. La diferencia está en que la retrollamada imprime un mensaje incluyendo los datos que se le pasan.

La línea 25 le pone un título en la barra de título de la ventana (mira la Figura 3.1. Ejemplo de Hola Mundo mejorado).

La línea 37 crea una caja horizontal (GtkHBox) para almacenar los dos botones que se crean en las líneas 43 y 58. La línea 40 añade la caja horizontal al contenedor de la ventana.

Las líneas 47 y 62 conectan el método callback() a la señal "clicked" de los botones. Cada botón establece una cadena diferente para que se le pase al método callback() cuando sea invocado.

Las líneas 51 y 64 empaquetan los botones en la caja horizontal. Las líneas 55 y 68 le dicen a GTK que muestren los botones.

Las líneas 69-70 le piden a GTK que muestre la caja y la ventana respectivamente.