0

在我的__init__功能中,我正在尝试做:

builder = gtk.Builder()
builder.add_from_file('main.glade')
builder.connect_signals(Handle())
self.list = builder.get_objects()

现在我想为我的 gui 中的所有小部件添加属性到我的类

for i in self.list:
    name = i.get_name()
    print name
    setattr(self, name, i)

我得到:

<gtk.VBox object at 0x2fd5558 (GtkVBox at 0x2499000)>
<gtk.Button object at 0x2fd5580 (GtkButton at 0x240a1a8)>
<gtk.Button object at 0x2fd55a8 (GtkButton at 0x240a130)>
<gtk.Button object at 0x2fd55d0 (GtkButton at 0x240a0b8)>
<gtk.Window object at 0x2fd55f8 (GtkWindow at 0x2495010)>
<gtk.HBox object at 0x2fd5620 (GtkHBox at 0x2499058)>
<gtk.Button object at 0x2fd5648 (GtkButton at 0x240a220)>
<gtk.TextView object at 0x2fd5670 (GtkTextView at 0x249d060)>

而不是我给这些小部件的具体名称

您对如何同时初始化所有小部件有想法吗?

4

2 回答 2

1

似乎没有办法获取小部件 ID 列表。您可以通过编写动态分配对象属性__getattr__

class Settings:
  """Settings dialog"""

  def __init__(self):
    self._log = _log.getChild(self.__class__.__name__)
    self.builder = Gtk.Builder()
    self.builder.add_from_file("settings.glade")
    self.builder.connect_signals(self)

  def __getattr__(self, name):
    self._log.debug("Resolving %s", name)
    obj = self.builder.get_object(name)
    setattr(self, name, obj)
    return obj
于 2013-02-09T16:44:47.490 回答
0

我不确定您所说的“初始化”是什么意思。AFAIK,当 Builder 加载 glade 文件时,对象已准备就绪。除非我误解,否则我认为您只需要获取 Glade 为其加载的小部件使用的名称。这可以通过 Buildable 接口访问,如下所示:

 name = gtk.Buildable(widget).get_name()
于 2012-04-14T21:56:45.240 回答