首页 > 解决方案 > Python Gtk:如何在 Treeview 中闪烁一行

问题描述

我有一个按钮,我希望所选行闪烁。有人应该单击闪烁按钮,然后单击事件to_blink启动一个线程,该线程_blink更改 3-6 str 元素的值MyTreeStore

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"

标签: pythongtkpygtkgtktreeview

解决方案


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

推荐阅读