理解 gi.repository

13 投票
2 回答
10293 浏览
提问于 2025-04-17 06:12

我在理解 gi.repository 的时候遇到了一些问题。

我在代码中使用了这个结构:

from gi.repository import Gtk

但是如果我想用某个组件,就会出现导入错误。

我搜索了一下,发现有些组件可以正常工作,比如 GtkSource、Vte、GLib 等等。

所以我的代码看起来是这样的:

from gi.repository import Gtk, GtkSource, Vte, GLib

一切都运行得很好,但如果我想添加 matplotlib 来在我的画布上绘图,就会出现错误。

    enter code/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py:40: Warning: specified class size for type `PyGtkGenericCellRenderer' is smaller than the parent type's `GtkCellRenderer' class size
  from gtk import _gtk
/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata: assertion `node != NULL' failed
  from gtk import _gtk
/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_ascii_strncasecmp: assertion `s2 != NULL' failed
  from gtk import _gtk
Segmentation fault (core dumped) here

我该如何让 matplotlib 和 gi.repository 一起工作呢?

谢谢!

2 个回答

13

看起来对Gtk3的支持最近刚刚添加上去。我想这可能需要一些时间才能在主要的版本中使用。

最好的办法就是下载并安装最新版本。

为了避免在我的Ubuntu 11.10上安装东西,我下载了backend_gtk3.py和backend_gtk3agg.py这两个文件,然后直接导入,像这样:

from gi.repository import Gtk

from matplotlib.figure import Figure
from backend_gtk3agg import FigureCanvasGTK3Agg as FigCanvas

我还需要修改backend_gtk3agg.py的第6行,原来的内容是:

import backend_agg

改成

from matplotlib.backends import backend_agg

,这样它就能从我安装的地方导入模块了。到目前为止,这个方法对我有效,但我知道这个解决方案可能不适用于不同版本的matplotlib。

6

这是个很好的问题。不过,我得告诉你,答案可能是“你不能这样做。”Matplotlib的GTK后端是为PyGTK写的,这是一种旧版的Python和GTK的连接方式。而gi.repository包则是新版的Python和GTK的连接方式。我不太确定这两者能不能混用,但从你的结果来看,似乎是不能的。

撰写回答