Mac OS 10.13.4下PyCharm虚拟环境运行matplotlib报错(关联Tkinter)
Hey there, let's sort out this matplotlib issue you're facing in your PyCharm virtual environment. The traceback cuts off, but based on what's shown—specifically the pylab_setup() call failing—this is almost certainly a backend compatibility problem, which is super common with older macOS versions + Python 2.7 combinations.
Here are the steps to fix it, ordered from quickest to more thorough:
1. Temporarily Override the Matplotlib Backend
The fastest test is to force matplotlib to use a backend that's more likely to work in your setup. Add these lines at the very top of your script:
import matplotlib matplotlib.use('TkAgg') # TkAgg is widely supported on older macOS import matplotlib.pyplot as plt
If TkAgg doesn't work, try replacing it with Qt4Agg or Qt5Agg (you'll need the corresponding PyQt packages installed, see step 2).
2. Install a Matplotlib Version Compatible with Python 2.7
Newer matplotlib versions dropped support for Python 2.7 entirely, so if you installed the latest version, that's a problem. Uninstall your current matplotlib and install the last stable release that supports Python 2.7:
# Activate your virtual environment first (if not already active) source /Users/sumeet/tensorflow/bin/activate # Uninstall existing matplotlib pip uninstall matplotlib -y # Install compatible version pip install matplotlib==2.2.5 # Optional: Install PyQt4 if you want to use Qt4Agg backend pip install pyqt4
Version 2.2.5 is the last major release that works reliably with Python 2.7 and Mac OS 10.13.4.
3. Verify PyCharm's Virtual Environment Configuration
Double-check that PyCharm is actually using your tensorflow virtual environment:
- Open PyCharm and go to
Preferences(orSettingson Windows/Linux) - Navigate to
Project: VISM>Project Interpreter - Make sure the selected interpreter is
/Users/sumeet/tensorflow/bin/python2.7(not the system Python) - If it's not, click the gear icon >
Add>Existing environmentand select the correct Python executable from your virtual env.
4. Fix Tkinter Dependencies (If Needed)
If the TkAgg backend throws an error about missing Tkinter, your system might be missing the Tk framework. Install it via Homebrew:
brew install tk
Then re-install matplotlib in your virtual environment to ensure it links against the newly installed Tk.
内容的提问来源于stack exchange,提问作者Sumeet Kumar

