解决Matplotlib保存/显示图像时的Gtk-Message模块加载警告问题
Hey there! That Gtk-Message warning can be super annoying even when your code works perfectly fine. Since reinstalling the appmenu modules didn't fix it, let's try some other approaches that usually resolve this on Ubuntu 22.04:
1. 切换Matplotlib的后端到QtAgg(推荐)
Since you already installed PyQt6, forcing Matplotlib to use the Qt backend instead of Gtk should bypass the Gtk module issue entirely. There are two ways to do this:
临时修改(仅当前脚本生效)
Add these lines at the very top of your script, before importing matplotlib:
import matplotlib matplotlib.use('QtAgg') import matplotlib.pyplot as plt
永久修改(全局生效)
First, find the location of your matplotlib configuration file by running this command in the terminal:
python3 -c "import matplotlib; print(matplotlib.matplotlib_fname())"
Open that file with a text editor, locate the line starting with backend: and change it to:
backend: QtAgg
Save the file and restart your Python environment for the change to take effect.
2. 临时禁用Gtk模块加载
You can exclude the problematic appmenu-gtk-module via an environment variable before running your script. Try executing your script like this:
GTK_MODULES=$(echo $GTK_MODULES | sed 's/appmenu-gtk-module//') python3 your_script.py
If you want this to apply permanently to all terminal sessions, add the following line to your ~/.bashrc or ~/.zshrc file:
export GTK_MODULES=$(echo $GTK_MODULES | sed 's/appmenu-gtk-module//')
Then run source ~/.bashrc (or the corresponding file for your shell) to activate the change.
3. 补充安装系统依赖
Sometimes missing system-level dependencies can cause module loading issues even after installing the main packages. Try installing these additional libraries:
sudo apt install libgtk-3-dev gir1.2-gtk-3.0
Reboot your system afterward and test your script again.
4. 使用无交互后端(仅保存图像时适用)
If you don't need to display plots with plt.show() and only want to save them, use the non-interactive Agg backend. Add this at the top of your script:
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt
This backend doesn't rely on any GUI libraries, so it won't trigger the Gtk warning at all.
Give these methods a shot—one of them should get rid of that pesky warning for you!
备注:内容来源于stack exchange,提问作者Jake Levi

