Este ejemplo es similar al de la , excepto que se usa Glade para crear la barra de herramientas en un archivo .ui XML.
Para crear la barra de herramientas usando el diseñador de interfaces Glade:
Abra Glade y guarde el archivo como
Bajo
Bajo la pestaña
Bajo la pestaña
Pulse el botón derecho sobre la barra de herramientas en la parte superior derecha y seleccione
Se quieren añadir 5 «ToolButton»: «New», «Open», «Undo», «Fullscreen», y «Leave Fullscreen». Primero, se añadirá el «ToolButton» «New».
Bajo la pestaña
Cambie el nombre del «ToolItem» a new_button.
Deslícese hacia abajo y establezca
Introduzca el
Cambie la
Seleccione el ID del inventario
Repita los pasos anteriores para los «ToolButton» restantes, con las siguientes propiedades:
Name |
Es importante |
Nombre de la acción |
Etiqueta |
ID del inventario |
open_button |
Sí |
app.open |
Open |
gtk-open |
undo_button |
Sí |
win.undo |
Undo |
gtk-undo |
fullscreen_button |
Sí |
win.fullscreen |
Fullscreen |
gtk-fullscreen |
leave_fullscreen_button |
Sí |
win.fullscreen |
Leave Fullscreen |
gtk-leave-fullscreen |
Cierre el
No se quiere que se vea el «ToolButton»
Guarde su trabajo y cierre Glade.
El archivo XML generado por Glade se muestra debajo. Este es la descripción de la barra de herramientas. En el momento en el que se escribe esto, la opción para añadir la clase «Gtk.STYLE_CLASS_PRIMARY_TOOLBAR» en el diseñador de interfaces Glade no existe. Se puede añadir manualmente al archivo XML. Para hacer esto, añada el siguiente código XML en la línea 9 de
<style>
<class name="primary-toolbar"/>
</style>
Si no añade esto, el programa seguirá funcionando bien. La barra de herramientas resultante se verá, sin embargo, ligeramente distinta a la de la captura de pantalla en la parte superior de esta página.
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<!-- interface-requires gtk+ 3.0 -->
<object class="GtkToolbar" id="toolbar">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="hexpand">True</property>
<property name="show_arrow">False</property>
<child>
<object class="GtkToolButton" id="new_button">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_action_appearance">False</property>
<property name="is_important">True</property>
<property name="action_name">app.new</property>
<property name="label" translatable="yes">New</property>
<property name="use_underline">True</property>
<property name="stock_id">gtk-new</property>
</object>
<packing>
<property name="expand">False</property>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<object class="GtkToolButton" id="open_button">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_action_appearance">False</property>
<property name="is_important">True</property>
<property name="action_name">app.open</property>
<property name="label" translatable="yes">Open</property>
<property name="use_underline">True</property>
<property name="stock_id">gtk-open</property>
</object>
<packing>
<property name="expand">False</property>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<object class="GtkToolButton" id="undo_button">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_action_appearance">False</property>
<property name="is_important">True</property>
<property name="action_name">win.undo</property>
<property name="label" translatable="yes">Undo</property>
<property name="use_underline">True</property>
<property name="stock_id">gtk-undo</property>
</object>
<packing>
<property name="expand">False</property>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<object class="GtkToolButton" id="fullscreen_button">
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="use_action_appearance">False</property>
<property name="is_important">True</property>
<property name="action_name">win.fullscreen</property>
<property name="label" translatable="yes">Fullscreen</property>
<property name="use_underline">True</property>
<property name="stock_id">gtk-fullscreen</property>
</object>
<packing>
<property name="expand">False</property>
<property name="homogeneous">True</property>
</packing>
</child>
<child>
<object class="GtkToolButton" id="leave_fullscreen_button">
<property name="use_action_appearance">False</property>
<property name="can_focus">False</property>
<property name="use_action_appearance">False</property>
<property name="is_important">True</property>
<property name="action_name">win.fullscreen</property>
<property name="label" translatable="yes">Leave Fullscreen</property>
<property name="use_underline">True</property>
<property name="stock_id">gtk-leave-fullscreen</property>
</object>
<packing>
<property name="expand">False</property>
<property name="homogeneous">True</property>
</packing>
</child>
</object>
</interface>
Ahora se crea el código siguiente, que añade la barra de herramientas desde el archivo que se acaba de crear.
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import Gio
import sys
class MyWindow(Gtk.ApplicationWindow):
def __init__(self, app):
Gtk.Window.__init__(self, title="Toolbar Example", application=app)
self.set_default_size(400, 200)
# a grid to attach the toolbar (see below)
grid = Gtk.Grid()
self.add(grid)
# we have to show the grid (and therefore the toolbar) with show(),
# as show_all() would show also the buttons in the toolbar that we want to
# be hidden (such as the leave_fullscreen button)
grid.show()
# a builder to add the UI designed with Glade to the grid:
builder = Gtk.Builder()
# get the file (if it is there)
try:
builder.add_from_file("toolbar_builder.ui")
except:
print("file not found")
sys.exit()
# and attach it to the grid
grid.attach(builder.get_object("toolbar"), 0, 0, 1, 1)
# two buttons that will be used later in a method
self.fullscreen_button = builder.get_object("fullscreen_button")
self.leave_fullscreen_button = builder.get_object(
"leave_fullscreen_button")
# create the actions that control the window, connect their signal to a
# callback method (see below), add the action to the window:
# undo
undo_action = Gio.SimpleAction.new("undo", None)
undo_action.connect("activate", self.undo_callback)
self.add_action(undo_action)
# and fullscreen
fullscreen_action = Gio.SimpleAction.new("fullscreen", None)
fullscreen_action.connect("activate", self.fullscreen_callback)
self.add_action(fullscreen_action)
# callback for undo
def undo_callback(self, action, parameter):
print("You clicked \"Undo\".")
# callback for fullscreen
def fullscreen_callback(self, action, parameter):
# check if the state is the same as Gdk.WindowState.FULLSCREEN, which
# is a bit flag
is_fullscreen = self.get_window().get_state(
) & Gdk.WindowState.FULLSCREEN != 0
if is_fullscreen:
self.unfullscreen()
self.leave_fullscreen_button.hide()
self.fullscreen_button.show()
else:
self.fullscreen()
self.fullscreen_button.hide()
self.leave_fullscreen_button.show()
class MyApplication(Gtk.Application):
def __init__(self):
Gtk.Application.__init__(self)
def do_activate(self):
win = MyWindow(self)
# show the window - with show() not show_all() because that would show also
# the leave_fullscreen button
win.show()
def do_startup(self):
Gtk.Application.do_startup(self)
# actions that control the application: create, connect their signal to a
# callback method (see below), add the action to the application
# new
new_action = Gio.SimpleAction.new("new", None)
new_action.connect("activate", self.new_callback)
app.add_action(new_action)
# open
open_action = Gio.SimpleAction.new("open", None)
open_action.connect("activate", self.open_callback)
app.add_action(open_action)
# callback for new
def new_callback(self, action, parameter):
print("You clicked \"New\".")
# callback for open
def open_callback(self, action, parameter):
print("You clicked \"Open\".")
app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)
Para ver los métodos útiles de un widget de barra de herramientas, consulte la
Gtk.Builder construye una interfaz desde una definición UI XML.
add_from_file(filename)
carga y procesa el archivo dado y lo une con el contenido actual del Gtk.Builder.
add_from_string(string)
procesa la cadena dada y la une con el contenido actual del Gtk.Builder.
add_objects_from_file(filename, object_ids)
es igual a add_from_file()
, pero solo carga los objetos con los ID dados en la lista de object_id
.
add_objects_from_string(string, object_ids)
es lo mismo que add_from_string()
, pero sólo carga los objetos con los ID dados en la lista de object_id
.
get_object(object_id)
obtiene el widget con el ID object_id
de los objetos cargados en el constructor.
get_objects()
devuelve todos los objetos cargados.
connect_signals(handler_object)
conecta las señales a los métodos dados en el handler_object
. Este puede ser cualquier objeto que contenga claves o atributos que se llamen como los nombres del manejador de señales dados en la descripción de la interfaz, por ejemplo una clase o un diccionario. En la línea 39 la señal "activate"
de la acción undo_action
se conecta a la función de retorno de llamada undo_callback()
usando action.connect(señal, función de retorno de llamada)
. Consulte la para una explicación más detallada.
En este ejemplo se usa lo siguiente:
GtkGrid
GtkBuilder
GtkWidget
Estructuras de eventos