带有matplotlib线程的GTK有时可以工作,而其他人则不能

时间:2018-06-20 02:18:55

标签: python matplotlib gtk3

我目前正在一个项目中,我希望在其中显示两个带有绘图的窗口。事实是,我在python和GTK上还很陌生,经过全面搜索并添加了一些我在网上找到的示例后,我设法使某些功能起作用。

我尝试的第一种方法是打开两个matplotlib图形,但是我必须关闭第一个图形才能看到第二个图形,因此我决定以另一种方式进行操作。

我决定创建一个函数,该函数创建带有绘图的窗口,然后创建两个不同的线程,每个线程中都有一个窗口(不知道为什么我认为这可能是个好主意)。

我第一次运行代码时,我真的很兴奋,因为它似乎起作用了。但是第二次我出错了。因此,代码有时可以正常运行,而其他时候则没有问题,并且编译器将引发错误。

然后我注意到,如果我在线程的开始之间放置一个“计时器”,为了在开始第二个线程之前等待,代码运行良好的次数增加了(尽管它并不总是有效的)

我得到的错误并不总是相同的,这里是一些:

错误1:

[xcb] Unknown request in queue while dequeuing
[xcb] Most likely this is a multi-threaded client and XInitThreads has 
not been called
[xcb] Aborting, sorry about that.
python: ../../src/xcb_io.c:165: dequeue_pending_request: Assertion 
`!xcb_xlib_unknown_req_in_deq' failed.
Gdk-Message: 22:53:19.047: mwe: Fatal IO error 11 (Resource 
temporarily unavailable) on X server :0.

错误2:

[xcb] Unknown request in queue while dequeuing
[xcb] Most likely this is a multi-threaded client and XInitThreads has 
not been called
[xcb] Aborting, sorry about that.
python: ../../src/xcb_io.c:165: dequeue_pending_request: Assertion 
`!xcb_xlib_unknown_req_in_deq' failed.
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

错误3:

Gdk-Message: 22:57:41.772: mwe: Fatal IO error 11 (Resource 
temporarily unavailable) on X server :0.
Process finished with exit code 1

我使用的是PyCharm,我的SO是Kubuntu。

这是我的代码的威力(可能充满了新手错误):

from threading import Thread
import time
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GLib, Gtk, GObject
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3cairo import 
FigureCanvasGTK3Cairo 
as FigureCanvas
from matplotlib.backends.backend_gtk3 import NavigationToolbar2GTK3 as NavigationToolbar

    def graph(x, y):
        win = Gtk.Window()
        win.connect("delete-event", Gtk.main_quit)
        win.set_default_size(400, 300)
        win.set_title("Embedding in GTK")
        f = Figure(figsize=(5, 4), dpi=100)
        a = f.add_subplot(111)
        a.plot(x, y)
        canvas = FigureCanvas(f)  # a Gtk.DrawingArea
        vbox = Gtk.VBox()
        win.add(vbox)
        vbox.pack_start(canvas, True, True, 0)
        toolbar = NavigationToolbar(canvas, win)
        vbox.pack_start(toolbar, False, True, 0)
        win.show_all()
        Gtk.main()

class MyThread(Thread):
    def __init__(self, thread_id):
            Thread.__init__(self)
            self.thread_id = thread_id

    def run(self):
            x = [1, 2, 3, 4]
            y = [2, 4, 6, 8]
            graph(x, y)

if __name__ == '__main__':
    GObject.threads_init()
    thread1 = MyThread(1)
    thread1.start()
    time.sleep(0.05)  # With 0.05 works almost every time.
    thread2 = MyThread(2)
    thread2.start()

如何使本次运行没有问题?还有另一种方法可以让两个窗口同时具有一个图?

希望您可以帮助我。并且,请让我知道您在代码中发现错误或不当的其他信息,我正在学习!

预先感谢

胡安

0 个答案:

没有答案