Gtk.Label
Gtk.Label — A widget that displays a small to medium amount of text
Object Hierarchy:
GObject
╰── GInitiallyUnowned
╰── Gtk.Widget
╰── Gtk.Misc
╰── Gtk.Label
╰── Gtk.AccelLabel
Functions:
- new
(str:str=None) -> Gtk.Widget
- set_text
(self, str:str)
- set_attributes
(self, attrs:Pango.AttrList=None)
- set_markup
(self, str:str)
- set_markup_with_mnemonic
(self, str:str)
- set_pattern
(self, pattern:str)
- set_justify
(self, jtype:Gtk.Justification)
- set_xalign
(self, xalign:float)
- set_yalign
(self, yalign:float)
- set_ellipsize
(self, mode:Pango.EllipsizeMode)
- set_width_chars
(self, n_chars:int)
- set_max_width_chars
(self, n_chars:int)
- set_line_wrap
(self, wrap:bool)
- set_line_wrap_mode
(self, wrap_mode:Pango.WrapMode)
- set_lines
(self, lines:int)
- get_layout_offsets
(self) -> x:int, y:int
- get_mnemonic_keyval
(self) -> int
- get_selectable
(self) -> bool
- get_text
(self) -> str
- new_with_mnemonic
(str:str=None) -> Gtk.Widget
- select_region
(self, start_offset:int, end_offset:int)
- set_mnemonic_widget
(self, widget:Gtk.Widget=None)
- set_selectable
(self, setting:bool)
- set_text_with_mnemonic
(self, str:str)
- get_attributes
(self) -> Pango.AttrList
- get_justify
(self) -> Gtk.Justification
- get_xalign
(self) -> float
- get_yalign
(self) -> float
- get_ellipsize
(self) -> Pango.EllipsizeMode
- get_width_chars
(self) -> int
- get_max_width_chars
(self) -> int
- get_label
(self) -> str
- get_layout
(self) -> Pango.Layout
- get_line_wrap
(self) -> bool
- get_line_wrap_mode
(self) -> Pango.WrapMode
- get_lines
(self) -> int
- get_mnemonic_widget
(self) -> Gtk.Widget
- get_selection_bounds
(self) -> bool, start:int, end:int
- get_use_markup
(self) -> bool
- get_use_underline
(self) -> bool
- get_single_line_mode
(self) -> bool
- get_angle
(self) -> float
- set_label
(self, str:str)
- set_use_markup
(self, setting:bool)
- set_use_underline
(self, setting:bool)
- set_single_line_mode
(self, single_line_mode:bool)
- set_angle
(self, angle:float)
- get_current_uri
(self) -> str
- set_track_visited_links
(self, track_links:bool)
- get_track_visited_links
(self) -> bool
Signals:
- “activate-current-link”
(label, user_data)
- “activate-link”
(label, uri, user_data)
- “copy-clipboard”
(label, user_data)
- “move-cursor”
(entry, step, count, extend_selection, user_data)
- “populate-popup”
(label, menu, user_data)
Description:
The Gtk.Label
widget displays a small amount of text. As the name implies, most labels are used to label another widget such as a
GtkButton, a Gtk.MenuItem, or a GtkComboBox.
Gtk.Label as Gtk.Buildable
The Gtk.Label implementation of the Gtk.Buildable interface supports a custom \name
, value
,
start
and end
and allows you to specify #PangoAttribute values for this label.
An example of a UI definition fragment specifying Pango attributes:
<object class="GtkLabel">
<attributes>
<attribute name="weight" value="PANGO_WEIGHT_BOLD"/>
<attribute name="background" value="red" start="5" end="10"/>"
</attributes>
</object>
The start and end attributes specify the range of characters to which the Pango attribute applies. If start and end are not specified, the attribute is applied to the whole text. Note that specifying ranges does not make much sense with translatable attributes. Use markup embedded in the translatable content instead.
Mnemonics
Labels may contain mnemonics
. Mnemonics are underlined characters in the label, used for keyboard navigation.
Mnemonics are created by providing a string with an underscore before the mnemonic character, such as "_File"
, to the functions Gtk.Label::new_with_mnemonic()
or
Gtk.Label::set_text_with_mnemonic()
.
Mnemonics automatically activate any activatable widget the label is inside, such as a Gtk.Button; if the label is not inside the mnemonic’s target widget, you have to tell the label about the target using Gtk.Label::set_mnemonic_widget()
.
Here’s a simple example where the label is inside a button:
# Pressing Alt+T will activate the label
button = Gtk.Button()
label = Gtk.Label.new_with_mnemonic("_Test")
button.add(label)
There’s a convenience function to create buttons with a mnemonic label:
# Pressing Alt+H will activate this button
button = Gtk.Button.new_with_mnemonic("_Hello")
To create a mnemonic for a widget alongside the label, such as a Gtk.Entry, you have to point the label at the entry with Gtk.Label::set_mnemonic_widget()
:
# Pressing Alt+H will focus the entry
entry = Gtk.Entry()
label = Gtk.Label.new_with_mnemonic("_Hello")
label.set_mnemonic_widget(entry)
Markup (styled text)
To make it easy to format text in a label (changing colors, fonts, etc.), label text can be provided in a simple [markup format][PangoMarkupFormat].
Here’s how to create a label with a small font:
label = Gtk.Label('Test and Hello')
label.set_markup("<small>Small text</small>")
(See [complete documentation][PangoMarkupFormat] of available tags in the Pango manual.)
The markup passed to Gtk.Label::set_markup()
must be valid; for example, literal \<, > and & characters must be escaped as <, >, and &.
If you pass text obtained from the user, file, or a network to Gtk.Label::set_markup()
, you’ll want to escape it with g_markup_escape_text() or g_markup_printf_escaped().
Markup strings are just a convenient way to set the #PangoAttrList on a label; Gtk.Label::set_attributes()
may be a simpler way to set attributes in some cases. Be careful though; #PangoAttrList tends to cause internationalization problems, unless you’re applying attributes to the entire string (i.e. unless you set the range of each attribute to [0, %G_MAXINT)). The reason is that specifying the start_index and end_index for a #PangoAttribute requires knowledge of the exact string being displayed, so translations will cause problems.
Selectable labels
Labels can be made selectable with Gtk.Label::set_selectable()
.
Selectable labels allow the user to copy the label contents to the clipboard. Only labels that contain useful-to-copy information — such as error messages — should be made selectable.
Text layout
A label can contain any number of paragraphs, but will have performance problems if it contains more than a small number.
Paragraphs are separated by newlines or other paragraph separators understood by Pango.
Labels can automatically wrap text if you call Gtk.Label::set_line_wrap()
.
Gtk.Label::set_justify()
sets how the lines in a label align with one another. If you want to set how the label as a whole aligns in its available space, see the Gtk.Widget::halign and can be used to control the size allocation of ellipsized or wrapped labels. For ellipsizing labels, if either is specified (and less than the actual text size), it is used as the minimum width, and the actual text size is used as the natural width of the label. For wrapping labels, width-chars is used as the minimum width, if specified, and max-width-chars is used as the natural width. Even if max-width-chars specified, wrapping labels will be rewrapped to use all of the available width.
Note that the interpretation of Gtk.Label::width-chars and [width-for-height geometry management.][geometry-management]
Links
Since 2.18, GTK+ supports markup for clickable hyperlinks in addition to regular Pango markup. The markup for links is borrowed from HTML, using the \<a\>
with href
and title
attributes. GTK+ renders links similar to the way they appear in web browsers, with colored, underlined text. The title
attribute is displayed as a tooltip on the link.
An example looks like this:
label = Gtk.Label('Test link')
label.set_markup("Go to the<a href=\"http://www.gtk.org\">GTK+ website</a> for more...")
It is possible to implement custom handling for links and their tooltips with the Gtk.Label::activate-link signal and the Gtk.Label::get_current_uri()
function.
Function Details:
new()
new (str:str=None) -> Gtk.Widget
Creates a new label with the given text inside it. You canpass None
to get an empty label widget.
- Returns: the new Gtk.Label
set_text()
set_text (self, str:str)
Sets the text within the Gtk.Label
widget. It overwrites any text thatwas there before.
This function will clear any previously set mnemonic accelerators, andset the “use-underline” property to FALSE
as a side effect.
This function will set the “use-markup” property to FALSE
as a side effect.
See also: Gtk.Label:set_markup()
set_attributes()
set_attributes (self, attrs:Pango.AttrList=None)
Sets a PangoAttrList; the attributes in the list are applied to thelabel text. The attributes set with this function will be appliedand merged with any other attributes previously effected by wayof the “use-underline” or “use-markup” properties.While it is not recommended to mix markup strings with manually setattributes, if you must; know that the attributes will be appliedto the label after the markup string is parsed.
set_markup()
set_markup (self, str:str)
Parses str
which is marked up with thePango text markup language, setting thelabel’s text and attribute list based on the parse results.
If the str
is external data, you may need to escape it withg_markup_escape_text()
or g_markup_printf_escaped()
:
const char format = "<span style=\"italic\">\%s</span>";char markup;markup = g_markup_printf_escaped (format, str);Gtk.Label:set_markup (GTK_LABEL (label), markup);g_free (markup);
This function will set the “use-markup” property to True
asa side effect.
If you set the label contents using the “label” property youshould also ensure that you set the “use-markup” propertyaccordingly.
See also: Gtk.Label:set_text()
set_markup_with_mnemonic()
set_markup_with_mnemonic (self, str:str)
Parses str
which is marked up with thePango text markup language,setting the label’s text and attribute list based on the parse results.If characters in str
are preceded by an underscore, they are underlinedindicating that they represent a keyboard accelerator called a mnemonic.
The mnemonic key can be used to activate another widget, chosenautomatically, or explicitly using Gtk.Label:set_mnemonic_widget()
.
set_pattern()
set_pattern (self, pattern:str)
The pattern of underlines you want under the existing text within theGtk.Label
widget. For example if the current text of the label says“FooBarBaz” passing a pattern of “ ” will underline“Foo” and “Baz” but not “Bar”.
set_justify()
set_justify (self, jtype:Gtk.Justification)
Sets the alignment of the lines in the text of the label relative toeach other. GTK_JUSTIFY_LEFT
is the default value when the widget isfirst created with Gtk.Label:new()
. If you instead want to set thealignment of the label as a whole, use `Gtk.Widget:set_halign
()instead.
Gtk.Label:set_justify()` has no effect on labels containing only asingle line.
set_xalign()
set_xalign (self, xalign:float)
Sets the “xalign” property for label
.
- Since: 3.16
set_yalign()
set_yalign (self, yalign:float)
Sets the “yalign” property for label
.
- Since: 3.16
set_ellipsize()
set_ellipsize (self, mode:Pango.EllipsizeMode)
Sets the mode used to ellipsize (add an ellipsis: "...") to the text if there is not enough space to render the entire string.
- Since: 2.6
set_width_chars()
set_width_chars (self, n_chars:int)
Sets the desired width in characters of label
to n_chars
.
- Since: 2.6
set_max_width_chars()
set_max_width_chars (self, n_chars:int)
Sets the desired maximum width in characters of label
to n_chars
.
- Since: 2.6
set_line_wrap()
set_line_wrap (self, wrap:bool)
Toggles line wrapping within the Gtk.Label
widget. True
makes it breaklines if text exceeds the widget’s size. FALSE
lets the text get cut offby the edge of the widget if it exceeds the widget size.
Note that setting line wrapping to True
does not make the labelwrap at its parent container’s width, because GTK+ widgetsconceptually can’t make their requisition depend on the parentcontainer’s size. For a label that wraps at a specific position,set the label’s width using `Gtk.Widget:set_size_request
()`.
set_line_wrap_mode()
set_line_wrap_mode (self, wrap_mode:Pango.WrapMode)
If line wrapping is on (see Gtk.Label:set_line_wrap()
) this controls howthe line wrapping is done. The default is PANGO_WRAP_WORD
which meanswrap on word boundaries.
- Since: 2.10
set_lines()
set_lines (self, lines:int)
Sets the number of lines to which an ellipsized, wrapping labelshould be limited. This has no effect if the label is not wrappingor ellipsized. Set this to -1 if you don’t want to limit thenumber of lines.
- Since: 3.10
get_layout_offsets()
get_layout_offsets (self) -> x:int, y:int
Obtains the coordinates where the label will draw the PangoLayoutrepresenting the text in the label; useful to convert mouse eventsinto coordinates inside the PangoLayout, e.g. to take some actionif some part of the label is clicked. Of course you will need tocreate a Gtk.EventBox
to receive the events, and pack the labelinside it, since labels are windowless (they return FALSE
from`Gtk.Widget:get_has_window
()). Rememberwhen using the PangoLayout functions you need to convert toand from pixels using
PANGO_PIXELS()` or PANGO_SCALE.
get_mnemonic_keyval()
get_mnemonic_keyval (self) -> int
If the label has been set so that it has an mnemonic key this functionreturns the keyval used for the mnemonic accelerator. If there is nomnemonic set up it returns GDK_KEY_VoidSymbol.
- Returns: GDK keyval usable for accelerators, or GDK_KEY_VoidSymbol
get_selectable()
get_selectable (self) -> bool
Gets the value set by Gtk.Label:set_selectable()
.
- Returns:
True
if the user can copy text from the label
get_text()
get_text (self) -> str
Fetches the text from a label widget, as displayed on thescreen. This does not include any embedded underlinesindicating mnemonics or Pango markup. (See Gtk.Label:get_label()
)
- Returns: the text in the label widget. This is the internalstring used by the label, and must not be modified.
new_with_mnemonic()
new_with_mnemonic (str:str=None) -> Gtk.Widget
Creates a new Gtk.Label
, containing the text in str
.
If characters in str
are preceded by an underscore, they areunderlined. If you need a literal underscore character in a label, use'__' (two underscores). The first underlined character represents a keyboard accelerator called a mnemonic. The mnemonic key can be used to activate another widget, chosen automatically, or explicitly usingGtk.Label:set_mnemonic_widget()
.
If Gtk.Label:set_mnemonic_widget()
is not called, then the first activatable ancestor of the Gtk.Label
will be chosen as the mnemonic widget. For instance, if the label is inside a button or menu item, the button or menu item will automatically become the mnemonic widget and be activated by the mnemonic.
- Returns: the new Gtk.Label
select_region()
select_region (self, start_offset:int, end_offset:int)
Selects a range of characters in the label, if the label is selectable.See Gtk.Label:set_selectable()
. If the label is not selectable,this function has no effect. If start_offset
orend_offset
are -1, then the end of the label will be substituted.
set_mnemonic_widget()
set_mnemonic_widget (self, widget:Gtk.Widget=None)
If the label has been set so that it has an mnemonic key (usingi.e. Gtk.Label:set_markup_with_mnemonic()
,Gtk.Label:set_text_with_mnemonic()
, Gtk.Label:new_with_mnemonic()
or the “use_underline” property) the label can be associated with awidget that is the target of the mnemonic. When the label is insidea widget (like a Gtk.Button
or a Gtk.Notebook
tab) it isautomatically associated with the correct widget, but sometimes(i.e. when the target is a Gtk.Entry
next to the label) you need toset it explicitly using this function.
The target widget will be accelerated by emitting the Gtk.Widget::mnemonic-activate
signal on it. The default handler for this signal will activate the widget if there are no mnemonic collisions and toggle focus between the colliding widgets otherwise.
set_selectable()
set_selectable (self, setting:bool)
Selectable labels allow the user to select text from the label, forcopy-and-paste.
set_text_with_mnemonic()
set_text_with_mnemonic (self, str:str)
Sets the label’s text from the string str
.If characters in str
are preceded by an underscore, they are underlinedindicating that they represent a keyboard accelerator called a mnemonic.The mnemonic key can be used to activate another widget, chosen automatically, or explicitly using Gtk.Label:set_mnemonic_widget()
.
get_attributes()
get_attributes (self) -> Pango.AttrList
Gets the attribute list that was set on the label usingGtk.Label:set_attributes()
, if any. This function doesnot reflect attributes that come from the labels markup(see Gtk.Label:set_markup()
). If you want to get theeffective attributes for the label, usepango_layout_get_attribute (Gtk.Label:get_layout (label)).
- Returns:
the attribute list, or
None
if none was set.
get_justify()
get_justify (self) -> Gtk.Justification
Returns the justification of the label. See Gtk.Label:set_justify()
.
- Returns: Gtk.Justification
get_xalign()
get_xalign (self) -> float
Gets the “xalign” property for label
.
Returns: the xalign property
Since: 3.16
get_yalign()
get_yalign (self) -> float
Gets the “yalign” property for label
.
Returns: the yalign property
Since: 3.16
get_ellipsize()
get_ellipsize (self) -> Pango.EllipsizeMode
Returns the ellipsizing position of the label. See Gtk.Label:set_ellipsize()
.
Returns: PangoEllipsizeMode
Since: 2.6
get_width_chars()
get_width_chars (self) -> int
Retrieves the desired width of label
, in characters. SeeGtk.Label:set_width_chars()
.
Returns: the width of the label in characters.
Since: 2.6
get_max_width_chars()
get_max_width_chars (self) -> int
Retrieves the desired maximum width of label
, in characters. SeeGtk.Label:set_width_chars()
.
Returns: the maximum width of the label in characters.
Since: 2.6
get_label()
get_label (self) -> str
Fetches the text from a label widget including any embeddedunderlines indicating mnemonics and Pango markup. (SeeGtk.Label:get_text()
).
- Returns: the text of the label widget. This string isowned by the widget and must not be modified or freed.
get_layout()
get_layout (self) -> Pango.Layout
Gets the PangoLayout used to display the label.The layout is useful to e.g. convert text positions topixel positions, in combination with Gtk.Label:get_layout_offsets()
.The returned layout is owned by the label
so need not befreed by the caller. The label
is free to recreate its layout atany time, so it should be considered read-only.
- Returns: the PangoLayout for this label.
get_line_wrap()
get_line_wrap (self) -> bool
Returns whether lines in the label are automatically wrapped. See Gtk.Label:set_line_wrap()
.
- Returns:
True
if the lines of the label are automatically wrapped.
get_line_wrap_mode()
get_line_wrap_mode (self) -> Pango.WrapMode
Returns line wrap mode used by the label. See Gtk.Label:set_line_wrap_mode()
.
Returns:
True
if the lines of the label are automatically wrapped.Since: 2.10
get_lines()
get_lines (self) -> int
Gets the number of lines to which an ellipsized, wrappinglabel should be limited. See Gtk.Label:set_lines()
.
Returns: The number of lines
Since: 3.10
get_mnemonic_widget()
get_mnemonic_widget (self) -> Gtk.Widget
Retrieves the target of the mnemonic (keyboard shortcut) of thislabel. See Gtk.Label:set_mnemonic_widget()
.
- Returns:
the target of the label’s mnemonic,or
None
if none has been set and the default algorithm will be used.
get_selection_bounds()
get_selection_bounds (self) -> bool, start:int, end:int
Gets the selected range of characters in the label, returning True
if there’s a selection.
- Returns:
True
if selection is non-empty
get_use_markup()
get_use_markup (self) -> bool
Returns whether the label’s text is interpreted as marked up withthe Pango text markup language.See Gtk.Label:set_use_markup()
.
- Returns:
True
if the label’s text will be parsed for markup.
get_use_underline()
get_use_underline (self) -> bool
Returns whether an embedded underline in the label indicates amnemonic. See Gtk.Label:set_use_underline()
.
- Returns:
True
whether an embedded underline in the label indicatesthe mnemonic accelerator keys.
get_single_line_mode()
get_single_line_mode (self) -> bool
Returns whether the label is in single line mode.
Returns:
True
when the label is in single line mode.Since: 2.6
get_angle()
get_angle (self) -> float
Gets the angle of rotation for the label. SeeGtk.Label:set_angle()
.
Returns: the angle of rotation for the label
Since: 2.6
set_label()
set_label (self, str:str)
Sets the text of the label. The label is interpreted asincluding embedded underlines and/or Pango markup dependingon the values of the “use-underline” and“use-markup” properties.
set_use_markup()
set_use_markup (self, setting:bool)
Sets whether the text of the label contains markup inPango’s text markup language.See Gtk.Label:set_markup()
.
set_use_underline()
set_use_underline (self, setting:bool)
If true, an underline in the text indicates the next character should beused for the mnemonic accelerator key.
set_single_line_mode()
set_single_line_mode (self, single_line_mode:bool)
Sets whether the label is in single line mode.
- Since: 2.6
set_angle()
set_angle (self, angle:float)
Sets the angle of rotation for the label. An angle of 90 reads fromfrom bottom to top, an angle of 270, from top to bottom. The anglesetting for the label is ignored if the label is selectable,wrapped, or ellipsized.
- Since: 2.6
get_current_uri()
get_current_uri (self) -> str
Returns the URI for the currently active link in the label.The active link is the one under the mouse pointer or, in aselectable label, the link in which the text cursor is currentlypositioned. This function is intended for use in a “activate-link” handleror for use in a “query-tooltip” handler.
Returns: the currently active URI. The string is owned by GTK+ and mustnot be freed or modified.
Since: 2.18
set_track_visited_links()
set_track_visited_links (self, track_links:bool)
Sets whether the label should keep track of clickedlinks (and use a different color for them).
- Since: 2.18
get_track_visited_links()
get_track_visited_links (self) -> bool
Returns whether the label is currently keeping trackof clicked links.
Returns:
True
if clicked links are rememberedSince: 2.18
Example:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class Label(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
self.set_default_size(600, -1)
self.connect("destroy", Gtk.main_quit)
grid = Gtk.Grid()
grid.set_border_width(5)
grid.set_row_spacing(5)
grid.set_column_spacing(5)
self.add(grid)
label = Gtk.Label("An example of a Label widget.")
label.set_selectable(True)
grid.attach(label, 0, 0, 1, 1)
label = Gtk.Label("This is a label spread across multiple\nlines using the newspace character\nto indicate the line break.")
grid.attach(label, 0, 1, 1, 1)
label = Gtk.Label("Tab spaces\tcan also be\tdefined if required.")
grid.attach(label, 0, 2, 1, 1)
label = Gtk.Label("Label widgets can also accept underline patterns.")
label.set_pattern("_____ _________")
label.set_line_wrap(True)
grid.attach(label, 0, 3, 1, 1)
label = Gtk.Label("Justification options are\nable to align text in the label,\nsuch as to the left.")
label.set_justify(Gtk.Justification.LEFT)
grid.attach(label, 1, 0, 1, 1)
label = Gtk.Label("Centering of text is possible\nto ensure that the margin\nof each sentence is even.")
label.set_justify(Gtk.Justification.CENTER)
grid.attach(label, 1, 1, 1, 1)
label = Gtk.Label("Text can also be right-justified\nto align to the right hand\nmargin of the label.")
label.set_justify(Gtk.Justification.RIGHT)
grid.attach(label, 1, 2, 1, 1)
label = Gtk.Label("Content is also justifiable to ensure that the sentences are evenly distributed. This ensures that the endings of each lines match. It does however require line wrapping to be enabled, and there are no manual breaks.")
label.set_line_wrap(True)
label.set_justify(Gtk.Justification.FILL)
grid.attach(label, 1, 3, 1, 1)
label = Gtk.Label("An angle can also be specified\nto orient the text.")
label.set_angle(90)
grid.attach(label, 2, 0, 1, 3)
label = Gtk.Label("<a href='http://programmica.com/'>A website link</a>")
label.set_use_markup(True)
grid.attach(label, 2, 3, 1, 1)
label = Label()
label.show_all()
Gtk.main()