Python:当主线程工作时,分离的Gtk线程没有响应

2024-06-16 11:05:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在帮助一个github项目开发一个位于ubuntu通知区的加密货币投币机。它使用libappindicator和gtk进行显示,并使用glib设置超时。你知道吗

完整的代码在这里:https://github.com/bluppfisk/coinprice-indicator/tree/separate_tickers

现在,由于Appindicator的限制,我决定从主线程为我显示的每个ticker运行一个新的Appindicator实例,并使用一个单独的Appindicator图标作为应用程序的“主菜单”。你知道吗

然后,因为Gtk.main()进程阻止我的脚本执行任何其他操作,我不能先加载主菜单,然后在数据进入时加载每个ticker。所以我决定在一个单独的线程中运行Gtk.main()。你知道吗

这工作得很好:首先加载主图标,然后主线程发出对股票信息的HTTP请求,一个appindicator接着一个appindicator在通知区域中显示正确的数据。你知道吗

但是,每当主线程启动这些HTTP连接时,我都无法触发用Gtk.AboutDialog()创建的About对话框。此外,About对话框上的close按钮以及任何其他UI元素只有在HTTP请求完成时才会做出反应。你知道吗

我以为在一个单独的线程中运行Gtk.main()会同时运行它?你知道吗

下面是一些有趣的代码:

import threading, gi
import from gi.repository Gtk, GdkPixbuf, GObject

try:
    from gi.repository import AppIndicator3 as AppIndicator
except ImportError:
    from gi.repository import AppIndicator

Class Coin(Object):

    def __init__(self):
        self.gui_ready = threading.Event()
        self.start_main()
        self.add_indicator()
        self.add_indicator()
        Gtk.main()

    def start_main()
        self.main_item = AppIndicator.Indicator.new(appname, icon, AppIndicator.IndicatorCategory.APPLICATION_STATUS)
        self.main_item.set_status(AppIndicator.IndicatorStatus.ACTIVE)
        self.main_item.set_label("", "")
        self.main_item.set_menu(self._menu())
        self.gui_thread = threading.Thread(target=self.start_gui_thread)
        self.gui_thread.start()
        self.gui_ready.wait()

    def start_gui_thread(self):
        GObject.threads_init()
        self.gui_ready.set()
        Gtk.main()

    def _menu(self):
        menu = Gtk.Menu()
        self.about_item = Gtk.MenuItem("About")
        self.about_item.connect("activate", self._about)

    def _about(self, widget):
        about = Gtk.AboutDialog()
        # rest of code to run dialog, incl. buttons to close

    def add_indicator(self, settings=None):
        indicator = Indicator(self, len(self.instances), self.config, settings)
        self.instances.append(indicator)

Tags: importselfgtkmaindefguiitemthread