Label (Python) Marta Maria Casetti mmcasetti@gmail.com 2012 Sebastian Pölsterl sebp@k-d-w.org 2012 A widget that displays a small to medium amount of text Label

A simple label

Code used to generate this example from gi.repository import Gtk import sys class MyWindow(Gtk.ApplicationWindow): # constructor for a Gtk.ApplicationWindow def __init__(self, app): Gtk.Window.__init__(self, title="Welcome to GNOME", application=app) self.set_default_size(200, 100) # create a label label = Gtk.Label() # set the text of the label label.set_text("Hello GNOME!") # add the label to the window self.add(label) class MyApplication(Gtk.Application): def __init__(self): Gtk.Application.__init__(self) def do_activate(self): win = MyWindow(self) win.show_all() def do_startup(self): Gtk.Application.do_startup(self) app = MyApplication() exit_status = app.run(sys.argv) sys.exit(exit_status)

Another way to obtain what we have in the example is to create the label as an instance of another class and add it to the instance of MyWindow in the do_activate(self) method:

The highlighted lines indicate code that is different from the previous snippet.

# a class to define a window class MyWindow(Gtk.ApplicationWindow): def __init__(self, app): Gtk.Window.__init__(self, title="Welcome to GNOME", application=app) self.set_default_size(200, 100) # a class to define a label class MyLabel(Gtk.Label): def __init__(self): Gtk.Label.__init__(self) self.set_text("Hello GNOME!") class MyApplication(Gtk.Application): def __init__(self): Gtk.Application.__init__(self) def do_activate(self): # create an instance of MyWindow win = MyWindow(self) # create an instance of MyLabel label = MyLabel() # and add it to the window win.add(label) # show the window and everything on it win.show_all()
Useful methods for a Label widget

An explanation of how to work with strings in GTK+ can be found in .

set_line_wrap(True) breaks lines if the text of the label exceeds the size of the widget.

set_justify(Gtk.Justification.LEFT) (or Gtk.Justification.RIGHT, Gtk.Justification.CENTER, Gtk.Justification.FILL) sets the alignment of the lines in the text of the label relative to each other. The method has no effect on a single-line label.

For decorated text we can use set_markup("text"), where "text" is a text in the Pango Markup Language. An example:

small, big, " "bold, italic and even point to somewhere " "on the internet.")]]>
API References

In this sample we used the following:

GtkLabel

GtkWindow