首页 > 解决方案 > 尽管使用 GObject.idle_add,python3 gtk3 GUI 仅部分更新

问题描述

我将 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 主循环迭代,但没有任何改变。

标签: pythonmultithreadinggtkpygobjectgobject

解决方案


推荐阅读