python 如何在运行时将项目添加到通过 Glade 创建的 gtk.ComboBox?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1176748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:39:27  来源:igfitidea点击:

How do I add items to a gtk.ComboBox created through glade at runtime?

pythongtkpygtk

提问by Bernard

I'm using Glade 3 to create a GtkBuilder file for a PyGTK app I'm working on. It's for managing bandwidth, so I have a gtk.ComboBox for selecting the network interface to track.

我正在使用 Glade 3 为我正在处理的 PyGTK 应用程序创建 GtkBuilder 文件。它用于管理带宽,所以我有一个 gtk.ComboBox 用于选择要跟踪的网络接口。

How do I add strings to the ComboBox at runtime? This is what I have so far:

如何在运行时向 ComboBox 添加字符串?这是我到目前为止:

self.tracked_interface = builder.get_object("tracked_interface")

self.iface_list_store = gtk.ListStore(gobject.TYPE_STRING)
self.iface_list_store.append(["hello, "])
self.iface_list_store.append(["world."])
self.tracked_interface.set_model(self.iface_list_store)
self.tracked_interface.set_active(0)

But the ComboBox remains empty. I tried RTFM'ing, but just came away more confused, if anything.

但是 ComboBox 仍然是空的。我尝试过 RTFM,但如果有的话,我会更加困惑。

Cheers.

干杯。

回答by Bernard

Hey, I actually get to answer my own question!

嘿,我实际上可以回答我自己的问题!

You have to add gtk.CellRendererText into there for it to actually render:

您必须将 gtk.CellRendererText 添加到其中才能实际呈现:

self.iface_list_store = gtk.ListStore(gobject.TYPE_STRING)
self.iface_list_store.append(["hello, "])
self.iface_list_store.append(["world."])
self.tracked_interface.set_model(self.iface_list_store)
self.tracked_interface.set_active(0)
# And here's the new stuff:
cell = gtk.CellRendererText()
self.tracked_interface.pack_start(cell, True)
self.tracked_interface.add_attribute(cell, "text", 0)

Retrieved from, of course, the PyGTK FAQ.

当然,从PyGTK FAQ 中检索。

Corrected example thanks to Joe McBride

感谢 Joe McBride 更正的示例

回答by Ivan Baldin

Or you could just create and insert the combo box yourself using gtk.combo_box_new_text(). Then you'll be able to use gtk shortcuts to append, insert, prependand removetext.

或者您可以使用gtk.combo_box_new_text(). 然后您将能够使用 gtk 快捷方式来附加插入前置删除文本。

combo = gtk.combo_box_new_text()
combo.append_text('hello')
combo.append_text('world')
combo.set_active(0)

box = builder.get_object('some-box')
box.pack_start(combo, False, False)