How can I create a GTK ComboBox with images in Python?

被刻印的时光 ゝ 提交于 2019-12-07 15:20:18

问题


How can I create a ComboBox that displays a list of entries, each containing some text and an icon?

I'm using Python and GTK3 with GObject introspection.


回答1:


Here's an example of how to do that, inspired by this answer for C.

from gi.repository import Gtk
from gi.repository import GdkPixbuf

store = Gtk.ListStore(str, GdkPixbuf.Pixbuf)

pb = GdkPixbuf.Pixbuf.new_from_file_at_size("picture.png", 32, 32)
store.append(["Test", pb])

combo = Gtk.ComboBox.new_with_model(store)

renderer = Gtk.CellRendererText()
combo.pack_start(renderer, True)
combo.add_attribute(renderer, "text", 0)

renderer = Gtk.CellRendererPixbuf()
combo.pack_start(renderer, False)
combo.add_attribute(renderer, "pixbuf", 1)

window = Gtk.Window()
window.add(combo)
window.show_all()

window.connect('delete-event', lambda w, e: Gtk.main_quit())

Gtk.main()



回答2:


The same example in GTK2, inspired by your code:

import pygtk
pygtk.require('2.0')
import gtk
import gtk.gdk
import gobject
import gc

store = gtk.ListStore(str, gtk.gdk.Pixbuf) 

pb = gtk.gdk.pixbuf_new_from_file("picture.png")
store.append(["Test", pb])

combo = gtk.ComboBox(store)

renderer = gtk.CellRendererText()
combo.pack_start(renderer, True)
combo.add_attribute(renderer, "text", 0)

renderer = gtk.CellRendererPixbuf()
combo.pack_start(renderer, False)
combo.add_attribute(renderer, "pixbuf", 1)

window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.add(combo)
window.show_all()

window.connect('delete-event', lambda w, e: gtk.main_quit())

gtk.main()


来源:https://stackoverflow.com/questions/15807611/how-can-i-create-a-gtk-combobox-with-images-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!