Python Gtk 应用程序中的线程

Threading in a Python Gtk Application

我正在尝试创建一个程序来显示来自陀螺仪的位置数据。为此,我一直在使用 threading.Thread 模块。我还必须使用 time.sleep() 来防止它立即崩溃。我的问题是 运行 一段时间后,程序有时会死机。它是这样实现的:

def get_gyro_data():
    return <the data from the gyro>

class Handler:
    def __init__(self):
        self.label = builder.get_object("my_label")
        threading.Thread(target=self.pos_data_update).start()

    def pos_data_update(self, *args):
        while True:
            self.label.set_text(get_gyro_data())
            time.sleep(.5)

有什么建议吗?还有什么方法可以不使用 time.sleep?

Gtk 不是线程安全的。对 GUI 的所有更改都应从主线程(运行主循环的线程)进行。

我喜欢使用以下功能:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GLib

def mainloop_do(callback, *args, **kwargs):
    def cb(_None):
        callback(*args, **kwargs)
        return False
    Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT, cb, None)

这允许您将工作传递给主线程,同时对代码进行最少的更改:

def pos_data_update(self, *args):
    while True:
        mainloop_do(self.label.set_text, get_gyro_data())
        time.sleep(.5)