Sólo hay una función para crear un control
TextView (Vista de Texto).
textview = gtk.TextView(buffer=None)
Cuando se crea una TextView también se creará
un TextBuffer
(Buffer de Texto) asociado y una TextTagTable (Tabla
de Etiquetas de Texto) de forma predeterminada. Si quieres usar un
TextBuffer ya
existente en una vista de texto TextView puedes especificarlo
en el método anterior. Para cambiar el
TextBuffer que
usa una TextView usa el siguiente método:
textview.set_buffer(buffer)
Usa el siguiente método para obtener una referencia al
TextBuffer a
partir de una TextView:
buffer = textview.get_buffer()
Un control de TextView no tiene barras de
desplazamiento para ajustar la vista en caso de que el texto sea más grande
que la ventana. Para incluir barras de desplazamiento, es necesario incluir la
TextView en una ScrolledWindow
(Ventana de Desplazamiento).
Una TextView se puede usar para permitir
la edición de un cuerpo de texto, o para mostrar varias líneas de
un texto de sólo lectura al usuario o usuaria. Para cambiar entre estos modos de
operación se utiliza el método:
textview.set_editable(setting)
El argumento setting puede ser TRUE
o FALSE y especifica si se permite la edición del contenido del control
TextView. El modo de edición de la
TextView se puede cambiar por zonas de texto dentro del
TextBuffer usando
TextTags.
Puedes obtener el modo actual de edición usando el método:
setting = textview.get_editable()
Cuando la TextView no es editable
probablemente se debería ocultar el cursor usando el método:
textview.set_cursor_visible(setting)
El argumento setting puede ser TRUE
o FALSE y
especifica si el cursor debe ser visible. La TextView
puede ajustar las líneas de texto que son demasiado largas para que quepan
en una única línea de la ventana. El comportamiento predeterminado es no
ajustar las líneas. Es posible cambiarlo usando el método:
textview.set_wrap_mode(wrap_mode)
Este método te permite especificar que el texto debe ajustarse en
los límites de palabras o caracteres. El argumento word_wrap
puede ser:
gtk.WRAP_NONE # sin ajuste gtk.WRAP_CHAR # ajuste por caracteres gtk.WRAP_WORD # ajuste por palabras
La justificación predetermianda del texto en una
TextView se puede establecer y obtener usando los métodos:
textview.set_justification(justification)
justification = textview.get_justification()
donde justification puede ser:
gtk.JUSTIFY_LEFT # justificación a la izquierda gtk.JUSTIFY_RIGHT # justificación a la derecha gtk.JUSTIFY_CENTER # justificación al centro
La justificación será JUSTIFY_LEFT si el
wrap_mode (modo de ajuste) es WRAP_NONE.
Las etiquetas asociadas con un
TextBuffer pueden
cambiar la justificación predeterminada.
Se pueden modificar y ver otros atributos predeterminados en una
TextView, tales como el margen izquierdo, el margen derecho,
las tabulaciones y la indentación de párrafos, usando los siguientes métodos:
# margen izquierdo textview.set_left_margin(left_margin) left_margin = textview.get_left_margin() # margen derecho textview.set_right_margin(right_margin) right_margin = textview.get_right_margin() # indentación textview.set_indent(indent) indent = textview.get_indent() #espacio anterior de línea (en píxeles) textview.set_pixels_above_lines(pixels_above_line) pixels_above_line = textview.get_pixels_above_lines() #espacio posterior de línea (en píxeles) textview.set_pixels_below_lines(pixels_below_line) pixels_below_line = textview.get_pixels_below_lines() # píxeles en ajuste textview.set_pixels_inside_wrap(pixels_inside_wrap) pixels_inside_wrap = textview.get_pixels_inside_wrap() # tabulaciones textview.set_tabs(tabs) tabs = textview.get_tabs()
left_margin, right_margin,
indent, pixels_above_lines,
pixels_below_lines y
pixels_inside_wrap se especifican en píxeles. Los valores
predeterminados de estos parámetros se pueden modificar con etiquetas
asociadas a un TextBuffer.
tabs es un pango.TabArray.
El programa de ejemplo textview-basic.py
ilustra el uso básico del control TextView:
El código fuente del programa es:
1 #!/usr/bin/env python
2
3 # example textview-basic.py
4
5 import pygtk
6 pygtk.require('2.0')
7 import gtk
8
9 class TextViewExample:
10 def toggle_editable(self, checkbutton, textview):
11 textview.set_editable(checkbutton.get_active())
12
13 def toggle_cursor_visible(self, checkbutton, textview):
14 textview.set_cursor_visible(checkbutton.get_active())
15
16 def toggle_left_margin(self, checkbutton, textview):
17 if checkbutton.get_active():
18 textview.set_left_margin(50)
19 else:
20 textview.set_left_margin(0)
21
22 def toggle_right_margin(self, checkbutton, textview):
23 if checkbutton.get_active():
24 textview.set_right_margin(50)
25 else:
26 textview.set_right_margin(0)
27
28 def new_wrap_mode(self, radiobutton, textview, val):
29 if radiobutton.get_active():
30 textview.set_wrap_mode(val)
31
32 def new_justification(self, radiobutton, textview, val):
33 if radiobutton.get_active():
34 textview.set_justification(val)
35
36 def close_application(self, widget):
37 gtk.main_quit()
38
39 def __init__(self):
40 window = gtk.Window(gtk.WINDOW_TOPLEVEL)
41 window.set_resizable(gtk.TRUE)
42 window.connect("destroy", self.close_application)
43 window.set_title("TextView Widget Basic Example")
44 window.set_border_width(0)
45
46 box1 = gtk.VBox(gtk.FALSE, 0)
47 window.add(box1)
48 box1.show()
49
50 box2 = gtk.VBox(gtk.FALSE, 10)
51 box2.set_border_width(10)
52 box1.pack_start(box2, gtk.TRUE, gtk.TRUE, 0)
53 box2.show()
54
55 sw = gtk.ScrolledWindow()
56 sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
57 textview = gtk.TextView()
58 textbuffer = textview.get_buffer()
59 sw.add(textview)
60 sw.show()
61 textview.show()
62
63 box2.pack_start(sw)
64 # Load the file textview-basic.py into the text window
65 infile = open("textview-basic.py", "r")
66
67 if infile:
68 string = infile.read()
69 infile.close()
70 textbuffer.set_text(string)
71
72 hbox = gtk.HButtonBox()
73 box2.pack_start(hbox, gtk.FALSE, gtk.FALSE, 0)
74 hbox.show()
75
76 vbox = gtk.VBox()
77 vbox.show()
78 hbox.pack_start(vbox, gtk.FALSE, gtk.FALSE, 0)
79 # check button to toggle editable mode
80 check = gtk.CheckButton("Editable")
81 vbox.pack_start(check, gtk.FALSE, gtk.FALSE, 0)
82 check.connect("toggled", self.toggle_editable, textview)
83 check.set_active(gtk.TRUE)
84 check.show()
85 # check button to toggle cursor visiblity
86 check = gtk.CheckButton("Cursor Visible")
87 vbox.pack_start(check, gtk.FALSE, gtk.FALSE, 0)
88 check.connect("toggled", self.toggle_cursor_visible, textview)
89 check.set_active(gtk.TRUE)
90 check.show()
91 # check button to toggle left margin
92 check = gtk.CheckButton("Left Margin")
93 vbox.pack_start(check, gtk.FALSE, gtk.FALSE, 0)
94 check.connect("toggled", self.toggle_left_margin, textview)
95 check.set_active(gtk.FALSE)
96 check.show()
97 # check button to toggle right margin
98 check = gtk.CheckButton("Right Margin")
99 vbox.pack_start(check, gtk.FALSE, gtk.FALSE, 0)
100 check.connect("toggled", self.toggle_right_margin, textview)
101 check.set_active(gtk.FALSE)
102 check.show()
103 # radio buttons to specify wrap mode
104 vbox = gtk.VBox()
105 vbox.show()
106 hbox.pack_start(vbox, gtk.FALSE, gtk.FALSE, 0)
107 radio = gtk.RadioButton(None, "WRAP__NONE")
108 vbox.pack_start(radio, gtk.FALSE, gtk.TRUE, 0)
109 radio.connect("toggled", self.new_wrap_mode, textview, gtk.WRAP_NONE)
110 radio.set_active(gtk.TRUE)
111 radio.show()
112 radio = gtk.RadioButton(radio, "WRAP__CHAR")
113 vbox.pack_start(radio, gtk.FALSE, gtk.TRUE, 0)
114 radio.connect("toggled", self.new_wrap_mode, textview, gtk.WRAP_CHAR)
115 radio.show()
116 radio = gtk.RadioButton(radio, "WRAP__WORD")
117 vbox.pack_start(radio, gtk.FALSE, gtk.TRUE, 0)
118 radio.connect("toggled", self.new_wrap_mode, textview, gtk.WRAP_WORD)
119 radio.show()
120
121 # radio buttons to specify justification
122 vbox = gtk.VBox()
123 vbox.show()
124 hbox.pack_start(vbox, gtk.FALSE, gtk.FALSE, 0)
125 radio = gtk.RadioButton(None, "JUSTIFY__LEFT")
126 vbox.pack_start(radio, gtk.FALSE, gtk.TRUE, 0)
127 radio.connect("toggled", self.new_justification, textview,
128 gtk.JUSTIFY_LEFT)
129 radio.set_active(gtk.TRUE)
130 radio.show()
131 radio = gtk.RadioButton(radio, "JUSTIFY__RIGHT")
132 vbox.pack_start(radio, gtk.FALSE, gtk.TRUE, 0)
133 radio.connect("toggled", self.new_justification, textview,
134 gtk.JUSTIFY_RIGHT)
135 radio.show()
136 radio = gtk.RadioButton(radio, "JUSTIFY__CENTER")
137 vbox.pack_start(radio, gtk.FALSE, gtk.TRUE, 0)
138 radio.connect("toggled", self.new_justification, textview,
139 gtk.JUSTIFY_CENTER)
140 radio.show()
141
142 separator = gtk.HSeparator()
143 box1.pack_start(separator, gtk.FALSE, gtk.TRUE, 0)
144 separator.show()
145
146 box2 = gtk.VBox(gtk.FALSE, 10)
147 box2.set_border_width(10)
148 box1.pack_start(box2, gtk.FALSE, gtk.TRUE, 0)
149 box2.show()
150
151 button = gtk.Button("close")
152 button.connect("clicked", self.close_application)
153 box2.pack_start(button, gtk.TRUE, gtk.TRUE, 0)
154 button.set_flags(gtk.CAN_DEFAULT)
155 button.grab_default()
156 button.show()
157 window.show()
158
159 def main():
160 gtk.main()
161 return 0
162
163 if __name__ == "__main__":
164 TextViewExample()
165 main()
Las líneas 10-34 definen las retrollamadas para los botones de
exclusión mútua y los botones de activación que se usan para cambiar los
atributos predeterminados de la TextView. Las líneas
55-63 crean una ScrolledWindow que
contenga la TextView. La ScrolledWindow se
empaqueta en una VBox con los botones que se crean en las
líneas 72-140. El TextBuffer asociado con
la TextView se rellena con el contenido del archivo
fuente en las líneas 64-70.