Tabla de contenidos
Ya hemos visto casi todo lo que hay que ver sobre el control de botón. Es bastante sencillo. Puedes usar la función gtk.Button() para crear un botón con una etiqueta pasándole un parámetro de cadena. Después depende de ti el empaquetar una etiqueta o un pixmap en este nuevo botón. Para hacer esto, crea una nueva caja, y después coloca tus objetos en esta caja usando el típico pack_start(), y después usa add() para colocar la caja dentro del botón.
La función para crear un botón es:
button = gtk.Button(label=None, stock=None) |
si se especifica una etiqueta esta se usa como texto del botón.Si se especifica stock este se usa para elegir un icono de stock y una etiqueta para el botón. Los elementos de stock son:
STOCK_DIALOG_INFO STOCK_DIALOG_WARNING STOCK_DIALOG_ERROR STOCK_DIALOG_QUESTION STOCK_DND STOCK_DND_MULTIPLE STOCK_ADD STOCK_APPLY STOCK_BOLD STOCK_CANCEL STOCK_CDROM STOCK_CLEAR STOCK_CLOSE STOCK_CONVERT STOCK_COPY STOCK_CUT STOCK_DELETE STOCK_EXECUTE STOCK_FIND STOCK_FIND_AND_REPLACE STOCK_FLOPPY STOCK_GOTO_BOTTOM STOCK_GOTO_FIRST STOCK_GOTO_LAST STOCK_GOTO_TOP STOCK_GO_BACK STOCK_GO_DOWN STOCK_GO_FORWARD STOCK_GO_UP STOCK_HELP STOCK_HOME STOCK_INDEX STOCK_ITALIC STOCK_JUMP_TO STOCK_JUSTIFY_CENTER STOCK_JUSTIFY_FILL STOCK_JUSTIFY_LEFT STOCK_JUSTIFY_RIGHT STOCK_MISSING_IMAGE STOCK_NEW STOCK_NO STOCK_OK STOCK_OPEN STOCK_PASTE STOCK_PREFERENCES STOCK_PRINT STOCK_PRINT_PREVIEW STOCK_PROPERTIES STOCK_QUIT STOCK_REDO STOCK_REFRESH STOCK_REMOVE STOCK_REVERT_TO_SAVED STOCK_SAVE STOCK_SAVE_AS STOCK_SELECT_COLOR STOCK_SELECT_FONT STOCK_SORT_ASCENDING STOCK_SORT_DESCENDING STOCK_SPELL_CHECK STOCK_STOP STOCK_STRIKETHROUGH STOCK_UNDELETE STOCK_UNDERLINE STOCK_UNDO STOCK_YES STOCK_ZOOM_100 STOCK_ZOOM_FIT STOCK_ZOOM_IN STOCK_ZOOM_OUT |
El programa de ejemplo buttons.py proporciona un ejemplo del uso de gtk.Button() para crear un botón con una imagen y una etiqueta dentro de él. He separado el código para crear una caja del resto para que puedas usarlo en tus programas. Hay más ejemplos del uso de imágenes más tarde en el tutorial. La figura Figura 6.1. Botón con Pixmap y Etiqueta muestra la ventana conteniendo un botón con un imágen y una etiqueta:
El código fuente del programa buttons.py es:
1 #!/usr/bin/env python
2
3 # example-start buttons buttons.c
4
5 import gtk
6
7 # Create a new hbox with an image and a label packed into it
8 # and return the box.
9
10 def xpm_label_box(parent, xpm_filename, label_text):
11 # Create box for xpm and label
12 box1 = gtk.HBox(gtk.FALSE, 0)
13 box1.set_border_width(2)
14
15 # Get the style of the button to get the
16 # background color.
17 style = parent.get_style()
18
19 # Now on to the image stuff
20 image = gtk.Image()
21 image.set_from_file(xpm_filename)
22
23 # Create a label for the button
24 label = gtk.Label(label_text)
25
26 # Pack the pixmap and label into the box
27 box1.pack_start(image, gtk.FALSE, gtk.FALSE, 3)
28 box1.pack_start(label, gtk.FALSE, gtk.FALSE, 3)
29
30 image.show()
31 label.show()
32 return box1
33
34 class Buttons:
35 # Our usual callback method
36 def callback(self, widget, data=None):
37 print "Hello again - %s was pressed" % data
38
39 def __init__(self):
40 # Create a new window
41 self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
42
43 self.window.set_title("Image'd Buttons!")
44
45 # It's a good idea to do this for all windows.
46 self.window.connect("destroy", lambda wid: gtk.main_quit())
47 self.window.connect("delete_event", lambda a1,a2:gtk.main_quit())
48
49 # Sets the border width of the window.
50 self.window.set_border_width(10)
51
52 # Create a new button
53 button = gtk.Button()
54
55 # Connect the "clicked" signal of the button to our callback
56 button.connect("clicked", self.callback, "cool button")
57
58 # This calls our box creating function
59 box1 = xpm_label_box(self.window, "info.xpm", "cool button")
60
61 # Pack and show all our widgets
62 button.add(box1)
63
64 box1.show()
65 button.show()
66
67 self.window.add(button)
68 self.window.show()
69
70 def main():
71 gtk.main()
72 return 0
73
74 if __name__ == "__main__":
75 Buttons()
76 main()
|
Las lineas 10-32 definen la función de ayuda xpm_label_box() que crea una caja horizontal con un borde de ancho 2 (lineas 12-13) y le pone una imagen (lineas 20-21) y una etiqueta (linea 24).
Las lineas 34-68 definen la clase Buttons Las lineas 39-68 definen el método de inicialización de instancia que crea una ventana (linea 41), le pone el título (linea 43), le conecta las señales "delete_event" y "destroy" (lineas 46-47). La linea 53 crea el botón sin etiqueta. Su señal "clicked" se conecta al método callback() en la linea 56. La función xpm_label_box() se llama en la linea 59 para crear la imagen y la etiqueta que se pondrán en el botón en la linea 62.
La función xpm_label_box() podría usarse para colocar archivos xpm y etiquetas en cualquier control que pueda ser un contenedor.
El control Botón tiene las siguientes señales:
pressed - se emite cuando el botón del puntero se presiona en el control Botón
released - se emite cuando el botón del puntero se suelta en el control Botón
clicked - se emite cuando el botón del puntero se presiona y luego se
suelta sobre el control Botón
enter - se emite cuando el puntero entra en el control Botón
leave - se emite cuando el puntero sale del control Botón
|