Python Gtk:如何在 Treeview 中闪烁一行

Python Gtk: How to get blink a row in a Treeview

我有一个按钮,我希望所选行闪烁。有人应该单击闪烁按钮,然后单击事件 to_blink启动一个线程 _blink,它会更改 MyTreeStore.

处的 3-6 str 元素的值
import threading
import time

class MyTreeStore(Gtk.TreeStore):
    def __init__(self):
        # i use the 3 last str's for the background colors
        Gtk.TreeStore.__init__(self, str, str, str, str, str, str)

 class TestBox(Gtk.VBox):
     def __init__(self): 

        self.treestore = MyTreeStore()
        self.treeview = Gtk.TreeView()
        self.treeview.set_model(self.treestore)

        renderer_col1 = Gtk.CellRendererText()
        column_1 = Gtk.TreeViewColumn("Col1", renderer_col1, text=0, cell_background=3)

        ...

        self.blink_button = Gtk.Button('Blink')
        self.is_connected_button.connect('clicked', self.to_blink)

   def to_blink(self, button):
    """ take certain row, start thread which change background-color """
       tree_selection = self.treeview.get_selection()
       tree_model, treepath = tree_selection.get_selected()

       if treepath:
           tree_model[treepath][3] = "green"
           tree_model[treepath][4] = "green"
           tree_model[treepath][5] = "green"

           t = threading.Thread(target=self._blink, args=(tree_model[treepath],))
           t.daemon = True
           t.start()

   def _blink(self, path):

       for i in range(100):
           path[3] = "green"
           path[4] = "green"
           path[5] = "green"
           time.sleep(1)
           path[3] = "white"
           path[4] = "white"
           path[5] = "white"

在使用 GTK 时应尽可能避免线程化。在这种情况下,这可以用 GLib.timeout_add 来解决。

替换:

        t = threading.Thread(target=self._blink, args=(tree_model[treepath],))
        t.daemon = True
        t.start()

有:

        GLib.timeout_add(1000, self._blink_glib, tree_model[treepath])

    def _blink_glib(self, path):
        for i in range(3, 6):
            if path[i] == "white":
                path[i] = "green"
            else:
                path[i] = "white"
        return True

回调需要 return True 继续或 False 停止。所以你仍然需要实现一个标志来指示是否完成了 100 次迭代。

另请注意:如果所有列都将以相同颜色闪烁,则不需要创建三个额外的 treestore 项目,只需一个就足够并将所有三个列的 cell_background 指向该项目。

        column_1 = Gtk.TreeViewColumn("Col1", renderer_col1, text=0, cell_background=3)
        column_2 = Gtk.TreeViewColumn("Col2", renderer_col2, text=0, cell_background=3)
        column_3 = Gtk.TreeViewColumn("Col3", renderer_col3, text=0, cell_background=3)

    def _blink_glib(self, path):
        path[3] = "green" if path[3] == "white" else "white"
        return True