Python 3和Gtk 3-TreeView和行的备用颜色存在问题

您好,我是Python 3.4.3.提前致谢!

#!/usr/bin/env python3
# -*- coding: ISO-8859-1 -*-
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk


xim = [("Oranges", 5), ("Apples", 3), ("Bananas", 1), ("Tomatoes", 4), ("Cucumber", 1), ("potatoes", 10),
       ("apricot", 100)]


window = Gtk.Window()
window.connect("destroy", lambda q: Gtk.main_quit())
liststore = Gtk.ListStore(str, int)
for i in range(len(xim)):
    liststore.append(xim[i])
treeview = Gtk.TreeView(model=liststore)
window.add(treeview)
treeviewcolumn = Gtk.TreeViewColumn("Item")
treeview.append_column(treeviewcolumn)
cellrenderertext = Gtk.CellRendererText()
treeviewcolumn.pack_start(cellrenderertext, True)
treeviewcolumn.add_attribute(cellrenderertext, "text", 0)
treeviewcolumn = Gtk.TreeViewColumn("Quantity")
treeview.append_column(treeviewcolumn)
cellrenderertext = Gtk.CellRendererText()
treeviewcolumn.pack_start(cellrenderertext, True)
treeviewcolumn.add_attribute(cellrenderertext, "text", 1)
css_provider = Gtk.CssProvider()
css = """
GtkTreeView row:nth-child(odd){background-color: #ccc}
            """
css_provider.load_from_data(css.encode())
Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(),
                                         css_provider,
                                         Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
window.show_all()
Gtk.main()

最佳答案

我知道使用CSS更改小部件的样式应该更好,但是还有另一种可行的解决方案.

在具有背景色值的ListStore中添加另一列,并将属性“ background”添加到两个CellRendererText中.这样,每一行都会从ListStore恢复背景属性.您应该为每行使用不同的颜色.

这是用我的技术修改过的代码:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk


xim = [("Oranges", 5), ("Apples", 3), ("Bananas", 1), ("Tomatoes", 4), ("Cucumber", 1), ("potatoes", 10),
       ("apricot", 100)]

window = Gtk.Window()
window.connect("destroy", lambda q: Gtk.main_quit())
liststore = Gtk.ListStore(str, int, str)
for i in range(len(xim)):
    if i % 2 == 0:
        background_color = "#fff"
    else:
        background_color = "#bbb"
    liststore.append(xim[i] + (background_color,))

treeview = Gtk.TreeView(model=liststore)
window.add(treeview)
treeviewcolumn = Gtk.TreeViewColumn("Item")
treeview.append_column(treeviewcolumn)
cellrenderertext = Gtk.CellRendererText()
treeviewcolumn.pack_start(cellrenderertext, True)
treeviewcolumn.add_attribute(cellrenderertext, "text", 0)
treeviewcolumn.add_attribute(cellrenderertext, "background", 2)

treeviewcolumn = Gtk.TreeViewColumn("Quantity")
treeview.append_column(treeviewcolumn)
cellrenderertext = Gtk.CellRendererText()
treeviewcolumn.pack_start(cellrenderertext, True)
treeviewcolumn.add_attribute(cellrenderertext, "text", 1)
treeviewcolumn.add_attribute(cellrenderertext, "background", 2)

window.show_all()
Gtk.main()