我正在使用Gtk3和线程模块,因为程序正在以未知的间隔从另一个程序接收消息。 更新GUI是在收到来自其他程序的消息后完成的,但由于某种原因并非所有内容都更新:Gtk.window.set_title工作正常,而Gtk.Box.pack_end不会在线程内更新。
这是我当前代码的简化版本(我删除了通信详细信息,因为它正常工作):
#! /usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GLib, Gtk, Gdk, GObject
import time
from threading import Thread
class AppWindow(Gtk.ApplicationWindow):
def __init__(self):
Gtk.Window.__init__(self)
self.grid = Gtk.Grid()
self.add(self.grid)
self.loop_box = Gtk.Box()
self.loop_box.set_vexpand(True)
self.grid.attach(self.loop_box, 0, 0, 1, 1)
new_info = Gtk.Label('lollerino1')
self.loop_box.pack_end(new_info, True, True, 0) # shown on GUI
self.communication_thread = Thread(target=self.manageIncomingCommunication)
self.communication_thread.setDaemon(True)
self.communication_thread.start()
def manageIncomingCommunication(self):
while True:
if (msg['type'] == "WORK!"):
GObject.idle_add(self.doGuiStuff, msg, priority=GObject.PRIORITY_DEFAULT)
time.sleep(1)
def doGuiStuff(self, msg_info):
Gtk.Window.set_title(self, 'I update correctly') # updates
new_info = Gtk.Label('lollerino2')
self.loop_box.pack_end(new_info, True, True, 0) # does not update GUI
# if I print here, printing is done correctly
Gtk.Window.resize(self, 500, 500) # also updates
app = AppWindow()
GObject.threads_init() # tried with and without
app.connect('destroy', Gtk.main_quit)
app.show_all()
Gtk.main()
我还试图在有待处理事件时手动添加gtk主循环迭代,但没有任何改变。