【问题标题】: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?如何在 Glade 中或在 Glade 中创建按钮后在代码中设置 Gtk.LinkBut​​ton 的标签,而无需手动编辑 .glade 文件?
【发布时间】:2026-01-20 06:00:02
【问题描述】:

我有一个 Gtk.LinkBut​​ton,我想在我正在编写的程序执行期间以编程方式更改它的标签。我发现我可以通过手动编辑 .glade 文件来更改标签。如何以编程方式更改它?我在最新的 MSYS2 和最新的 Windows 10 中使用 Python 2.7.13 和 GTK+ 3.22。

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>

截图

【问题讨论】:

    标签: python-2.7 gtk windows-10 gtk3 msys2


    【解决方案1】:

    由于Gtk.LinkButton父类是Gtk.Button,你可以使用Gtk.Buttonset_label方法来设置按钮标签:

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

    PS:GObject 属性封装在&lt;object&gt;.props.&lt;property&gt; 中,因此,使用与问题相同的方法设置标签,应该这样做:

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

    【讨论】: