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

时间:2019-04-02 09:21:00

标签: python gtk pygtk gtktreeview

我有一个按钮,希望所选的行闪烁。有人应单击“闪烁”按钮,然后单击事件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"

1 个答案:

答案 0 :(得分:1)

使用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

回调需要返回True才能继续进行,或者需要返回False来停止。因此,您仍然必须实现一个标志来指示是否完成了100次迭代。

另一个需要注意的是:如果所有列将以相同的颜色闪烁,则不需要创建三个额外的树存储项目,只需一个就足够并将所有三列的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