Python 3和Gtk + 3 - TreeView和行的替代颜色问题

时间:2016-11-23 10:31:25

标签: python python-3.x treeview gtk3

您好我是python和Gtk + 3开发的新手。我正在尝试用Gtk + 3创建一个包含Gtk.TreeView的Gui。我试图以不同的颜色显示TreeView的奇怪记录,但我总是失败。我搜索了整个互联网和StackOverFlow,但我没有找到有用的东西。所以我求求你的帮助。 我正在使用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()

1 个答案:

答案 0 :(得分:4)

我知道使用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()