Label

Code used to generate this example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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 Strings.

  • 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:

    label.set_markup("Text can be <small>small</small>, <big>big</big>, "
                     "<b>bold</b>, <i>italic</i> and even point to somewhere "
                     "on the <a href=\"http://www.gtk.org\" "
                     "title=\"Click to find out more\">internet</a>.")

API References

In this sample we used the following: