python - 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"
解决方案
使用 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
推荐阅读
- node.js - 拒绝来自 base64 编码器的无效 URL
- flutter - 您如何在一个屏幕上截屏并将该屏幕截图(图像文件)传递到 Flutter 中的另一个屏幕
- django - 为什么 Django 使用错误的 MIME 类型提供静态文件?
- android - 为根文件夹 (/) 设置可读权限以执行 listFiles()
- python - 使用嵌套字典列表过滤数据框
- sql - 按值获取数据库中的最后修改日期
- azure-data-factory - 如何重命名 ADF 中的文件名?
- nodes - networkx 算法中是否有一个函数可以返回我指定的某些节点周围的集团/集群/组件?
- c++ - 为什么这个核心转储错误发生在我的课堂上?我已经包含了复制构造函数、复制赋值和析构函数
- gis - 在 NetLogo 中创建网络后隐藏道路 shapefile