Search code examples
python-2.7gtkwindows-10gtk3msys2

How to set the label of a Gtk.LinkButton in Glade or in code after creating the button in Glade, without manually editing the .glade file?


I have a Gtk.LinkButton and I want to change it's label programatically during the execution of the program I am writing. I have found out that I can change the label by manually editing the .glade file. How can I change it programatically? I use Python 2.7.13 and GTK+ 3.22 inside up to date MSYS2 and up to date Windows 10.

example.py:

# coding=utf-8

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

b = Gtk.Builder()
b.add_from_file("test.glade")

w = b.get_object("window1")
linkButton = b.get_object("linkButton")
linkButton.label = "Google"  # This does nothing.

w.connect("delete-event", Gtk.main_quit)
w.show_all()
Gtk.main()

test.glade:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.20.0 -->
<interface>
  <requires lib="gtk+" version="3.20"/>
  <object class="GtkWindow" id="window1">
    <property name="can_focus">False</property>
    <child>
      <object class="GtkLinkButton" id="linkButton">
        <property name="label" translatable="yes">button</property>
        <property name="visible">True</property>
        <property name="can_focus">True</property>
        <property name="receives_default">True</property>
        <property name="relief">none</property>
        <property name="uri">http://www.google.com</property>
      </object>
    </child>
  </object>
</interface>

Screenshot:

Screenshot


Solution

  • Since Gtk.LinkButton parent class is Gtk.Button you can use Gtk.Button set_label method to set the button label:

    ...
    w = b.get_object("window1")
    linkButton = b.get_object("linkButton")
    linkButton.set_label("Google")  # This does something
    ...
    

    PS: GObject properties are encapsulated in <object>.props.<property>, so, to set the label using the same approach as the question does, one should do:

    linkButton.props.label = "Google"  # This also does something