获取Matplotlib的GTK Agg后端以尊重用户主题

det*_*tly 7 pygtk matplotlib

我正在编写一个使用Matplotlib进行绘图的PyGTK/Twisted应用程序.使用FigureCanvasGtkAgg将图块嵌入到我的小部件中很容易,但是我注意到画布的背景颜色(在绘图区域本身之外)与我的应用程序的其余部分不匹配,并且字体也没有(对于标签) ,传说等).

有没有一种简单的方法让我的图表尊重用户选择的GTK主题?

tkf*_*tkf 3

您可以通过例如pylab.figure(facecolor=SOME_COLOR, ...)或进行设置matplotlib.rcParams['figure.facecolor'] = SOME_COLOR。看起来它的默认值是硬编码的,因此无法告诉 MPL 尊重 GTK 主题。


下面是如何在 PyGTK 中执行此操作的具体示例。这里的一些信息是从“获取当前 gtk 样式的颜色”gdk.Color文档中收集的。我还没有了解设置字体等,但这显示了您需要的基本框架。

首先,定义以下函数:

def set_graph_appearance(container, figure):
    """
    Given a GTK container and a Matplotlib "figure" object, this will set the
    figure background colour to be the same as the normal colour of the
    container.
    """
    # "bg" is the background "style helper" object. It contains five different
    # colours, for the five different widget states.
    bg_style = container.get_style().bg[gtk.STATE_NORMAL]
    gtk_color = (bg_style.red_float, bg_style.green_float, bg_style.blue_float)
    figure.set_facecolor(gtk_color)
Run Code Online (Sandbox Code Playgroud)

然后,您可以连接到realize信号(也许也是map-event信号,我没有尝试)并在创建包含的小部件时重新为图形着色:

graph_panel.connect('realize', set_graph_appearance, graph.figure)
Run Code Online (Sandbox Code Playgroud)

(这里,graph_panel是 agtk.Alignment并且graph是它的子类,根据需要FigureCanvasGTKAgg有一个成员。)figure

  • 伟大的!这让我开始了,所以我添加了一些代码来说明如何在绘制时将背景更改为包含的小部件的 GTK 主题。唯一的问题是,如果用户在绘制图表后更改主题,图表将不会改变颜色。我认为这是一个足够小的边缘情况,可以忽略。 (3认同)