【发布时间】:2014-09-15 10:57:09
【问题描述】:
我只是想在调试时使用matplotlib来可视化一些数据。关注此页面:Analyzing C/C++ matrix in the gdb debugger with Python and Numpy - CodeProject,它可以正常工作,除非 matplotlib GUI 只是阻止 GDB 的命令行。这意味着如果我让 GUI 窗口保持打开状态,GDB 的命令行将被冻结,并且在关闭 pyplot 窗口之前我无法在 GDB 命令中输入任何内容。
为了解决这个问题,我只是尝试在另一个线程中运行绘图代码,为了简化测试用例,我只是创建了一个名为“test-pyplot.py”的简单python源代码,内容如下
import numpy as np
from matplotlib import pyplot as plt
from threading import Thread
class MyThread (Thread):
def __init__(self, thread_id):
Thread.__init__(self)
self.thread_id = thread_id
def run(self):
x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.plot(x, y)
plt.show(block = True) #this cause the mainloop
thread1 = MyThread(1)
thread1.start()
现在,在 GDB 命令行下,我只需键入:source test-pyplot.py,就会打开一个非阻塞的 GUI,看起来不错,GDB 的命令行仍然可以接受命令,到目前为止一切顺利。
但是当我关闭绘图窗口时出现问题,然后我再次运行source test-pyplot.py,这一次,GDB 只是挂起。
我在 Windows 下使用 python 2.7.6,我看到 matplotlib 默认使用 tkAgg 作为绘图后端,所以我尝试看看这是否会发生在普通的 tk GUI 窗口中。这是另一个名为“test-tk.py”的测试python文件,其内容如下:
from Tkinter import *
from threading import Thread
class App():
def __init__(self):
self.g=Tk()
self.th=Thread(target=self.g.mainloop)
self.th.start()
def destroy(self):
self.g.destroy()
a1 = App()
如果我在 GDB 提示符下运行命令source test-tk.py,会出现一个 tk 窗口,GDB 仍然存在(未冻结),我可以关闭 tk 窗口,然后再次输入命令 source test-tk.py,然后每次一切正常,GDB 没有挂起。我什至可以在不关闭第一个 tk 窗口的情况下运行命令 source test-tk.py 两次,然后会显示两个 tk 窗口。
问题:如何在非阻塞模式下正确显示matplotlib pyplot图形,不挂GDB?谢谢。
通常plt.show会在内部调用Tkinter包的mainloop函数,这是一个事件循环。
matplotlib 确实有一个名为交互模式的选项,可以通过调用 `plt.ion()' 来启用它,但它不能解决我的问题。
【问题讨论】:
标签: python matplotlib tkinter gdb pretty-print