Las barras de progreso se usan para mostrar el estado de una operación. Son bastante fáciles de usar, como verás en el código que sigue. Pero primero empecemos con una llamada para crar una nueva barra de progreso.
progressbar = gtk.ProgressBar(adjustment=None)
|
El argumento adjustment (ajuste) especifica un ajusta para usarlo con la barra de progreso. Si no se especifica se creará un ajuste. Ahora la barra de progreso está creada y podemos usarla.
progressbar.set_fraction(fraction) |
El objeto progressbar es la barra de progreso con la que queremos operar, y el argumento (fraction) es la cantidad "completada", lo que significa la cantidad con la que se ha rellenado la barra de progreso desde 0 a 100%. Esto se le pasa al método como un número real entre 0 y 1.
Una barra de progreso puede orientarse de diversas formas usando el mmétodo:
progressbar.set_orientation(orientation) |
El argumento orientation puede tomar uno de los siguientes valores para indicar la dirección en la que la barra de progreso se mueve:
PROGRESS_LEFT_TO_RIGHT # izquierda a derecha PROGRESS_RIGHT_TO_LEFT # derecha a izquierda PROGRESS_BOTTOM_TO_TOP # abajo a arriba PROGRESS_TOP_TO_BOTTOM # arriba a abajo |
Además de indicar la cantidad de progreso que se ha completado, la barra de progreso también puede usarse para indicar que ha habido alguna actividad. Esto puede ser útil en situaciones donde el progreso no se puede medir con un rango de valores. La siguiente función indica que se ha hecho algún progreso.
progressbar.pulse() |
El tamaño de paso de un indicador de actividad se establece usando la siguiente función, donde la fracción es un número entre 0.0 y 1.0.
progressbar.set_pulse_step(fraction)
|
Cuando no está en el modo actividad, la barra de progreso también puede mostrar una cadena de texto en su canal, usando el siguiente método:
progressbar.set_text(text)
|
Ten en cuenta que set_text() no soporta el formateo de texto al estilo printf() como lo hacía la barra de progreso de GTK+ 1.2.
Puedes desactivar la visualización de la cadena llamando a set_text() otra vez sin argumentos.
La cadena de texto actual de la barra de progreso se puede obtener con el siguiente método:
text = progressbar.get_text() |
Normalmente las Barras de Progreso usan cronómetros u otras funciones parecidas (mira la sección sobre Cronómetros, E/S y Funciones de Inactividad) para dar la ilusión de multitarea. Todas usarán los métodos set_fraction() o pulse() de la misma forma.
El programa progressbar.py proporciona un ejemplo de barra de progreso, actualizada usando cronómetros. Este código también muestra como reiniciar la Barra de Progreso. La figura Figura 9.4. Ejemplo de Barra de Progreso muestra la ventana resultante:
El código fuente del programa progressbar.py es:
1 #!/usr/bin/env python
2
3 # example progressbar.py
4
5 import gtk
6
7 # Update the value of the progress bar so that we get
8 # some movement
9 def progress_timeout(pbobj):
10 if pbobj.activity_check.get_active():
11 pbobj.pbar.pulse()
12 else:
13 # Calculate the value of the progress bar using the
14 # value range set in the adjustment object
15 new_val = pbobj.pbar.get_fraction() + 0.01
16 if new_val > 1.0:
17 new_val = 0.0
18 # Set the new value
19 pbobj.pbar.set_fraction(new_val)
20
21 # As this is a timeout function, return TRUE so that it
22 # continues to get called
23 return gtk.TRUE
24
25 class ProgressBar:
26 # Callback that toggles the text display within the progress
27 # bar trough
28 def toggle_show_text(self, widget, data=None):
29 if widget.get_active():
30 self.pbar.set_text("some text")
31 else:
32 self.pbar.set_text("")
33
34 # Callback that toggles the activity mode of the progress
35 # bar
36 def toggle_activity_mode(self, widget, data=None):
37 if widget.get_active():
38 self.pbar.pulse()
39 else:
40 self.pbar.set_fraction(0.0)
41
42 # Callback that toggles the orientation of the progress bar
43 def toggle_orientation(self, widget, data=None):
44 if self.pbar.get_orientation() == gtk.PROGRESS_LEFT_TO_RIGHT:
45 self.pbar.set_orientation(gtk.PROGRESS_RIGHT_TO_LEFT)
46 elif self.pbar.get_orientation() == gtk.PROGRESS_RIGHT_TO_LEFT:
47 self.pbar.set_orientation(gtk.PROGRESS_LEFT_TO_RIGHT)
48
49 # Clean up allocated memory and remove the timer
50 def destroy_progress(self, widget, data=None):
51 gtk.timeout_remove(self.timer)
52 self.timer = 0
53 gtk.mainquit()
54
55 def __init__(self):
56 self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
57 self.window.set_resizable(gtk.TRUE)
58
59 self.window.connect("destroy", self.destroy_progress)
60 self.window.set_title("ProgressBar")
61 self.window.set_border_width(0)
62
63 vbox = gtk.VBox(gtk.FALSE, 5)
64 vbox.set_border_width(10)
65 self.window.add(vbox)
66 vbox.show()
67
68 # Create a centering alignment object
69 align = gtk.Alignment(0.5, 0.5, 0, 0)
70 vbox.pack_start(align, gtk.FALSE, gtk.FALSE, 5)
71 align.show()
72
73 # Create the ProgressBar using the adjustment
74 self.pbar = gtk.ProgressBar()
75
76 align.add(self.pbar)
77 self.pbar.show()
78
79 # Add a timer callback to update the value of the progress bar
80 self.timer = gtk.timeout_add (100, progress_timeout, self)
81
82 separator = gtk.HSeparator()
83 vbox.pack_start(separator, gtk.FALSE, gtk.FALSE, 0)
84 separator.show()
85
86 # rows, columns, homogeneous
87 table = gtk.Table(2, 2, gtk.FALSE)
88 vbox.pack_start(table, gtk.FALSE, gtk.TRUE, 0)
89 table.show()
90
91 # Add a check button to select displaying of the trough text
92 check = gtk.CheckButton("Show text")
93 table.attach(check, 0, 1, 0, 1,
94 gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL,
95 5, 5)
96 check.connect("clicked", self.toggle_show_text)
97 check.show()
98
99 # Add a check button to toggle activity mode
100 self.activity_check = check = gtk.CheckButton("Activity mode")
101 table.attach(check, 0, 1, 1, 2,
102 gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL,
103 5, 5)
104 check.connect("clicked", self.toggle_activity_mode)
105 check.show()
106
107 # Add a check button to toggle orientation
108 check = gtk.CheckButton("Right to Left")
109 table.attach(check, 0, 1, 2, 3,
110 gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL,
111 5, 5)
112 check.connect("clicked", self.toggle_orientation)
113 check.show()
114
115 # Add a button to exit the program
116 button = gtk.Button("close")
117 button.connect("clicked", self.destroy_progress)
118 vbox.pack_start(button, gtk.FALSE, gtk.FALSE, 0)
119
120 # This makes it so the button is the default.
121 button.set_flags(gtk.CAN_DEFAULT)
122
123 # This grabs this button to be the default button. Simply hitting
124 # the "Enter" key will cause this button to activate.
125 button.grab_default ()
126 button.show()
127
128 self.window.show()
129
130 def main():
131 gtk.main()
132 return 0
133
134 if __name__ == "__main__":
135 ProgressBar()
136 main()
|