我正在尝试将组合框应用到一个小的GTK3接口,但我无法弄清楚如何填充它的列表,以及如何将接口的组合框与我的python代码连接起来.
有人能告诉我一个小例子吗?其余部分我将能够完成.
ComboBox,如TextViews或TreeViews,是一个小部件,可以清楚地将View(它看起来像什么)与模型分开(它们拥有什么信息).你需要在Glade做:
将Combobox添加到GUI中的某个位置.
创建一个将保存数据的ListStore.将Liststore配置为您需要的任何列(每列都有一个类型).
返回组合框,将之前创建的Liststore设置为模型.
编辑组合框(右键单击,编辑)并添加单元格渲染器.映射单元格渲染器以显示模型某些列的数据.
如果您的数据是静态的,那么您可以在Glade中向ListStore添加行.如果您的数据是动态的,则需要在代码中获取liststore,然后使用与liststore具有相同类型元素的列表填充它.
我能想到的一个较小的例子就是这个:
test.glade
test.py
from gi.repository import Gtk from os.path import abspath, dirname, join WHERE_AM_I = abspath(dirname(__file__)) class MyApp(object): def __init__(self): # Build GUI self.builder = Gtk.Builder() self.glade_file = join(WHERE_AM_I, 'test.glade') self.builder.add_from_file(self.glade_file) # Get objects go = self.builder.get_object self.window = go('window') self.myliststore = go('myliststore') self.mycombobox = go('mycombobox') # Initialize interface colors = [ ['#8C1700', 'Redish'], ['#008C24', 'Greenish'], ['#6B6BEE', 'Blueish'], ] for c in colors: self.myliststore.append(c) self.mycombobox.set_active(0) # Connect signals self.builder.connect_signals(self) # Everything is ready self.window.show() def main_quit(self, widget): Gtk.main_quit() def combobox_changed(self, widget, data=None): model = widget.get_model() active = widget.get_active() if active >= 0: code = model[active][0] print('The code of the selected color is {}'.format(code)) else: print('No color selected') if __name__ == '__main__': try: gui = MyApp() Gtk.main() except KeyboardInterrupt: pass
亲切的问候