1. 程式人生 > >pyenv下使用python matplotlib模組的問題解決

pyenv下使用python matplotlib模組的問題解決

錯誤資訊

先來描述一下我遇到的問題,在進行matplotlib學習時,plot.show()總是無法成功執行,總是會報一個錯:

RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework.See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.

其實意思很簡單,就是我用的python並不是一個作為系統框架存在的,因為我為了方便管理python的版本,選擇了pyenv這個管理工具,是一個獨立出來的python環境。

嘗試解決無果

參考網上眾多的解決方法,例如以下兩個最常見的:

方法一: 新增如下兩行 程式碼解決:

>>> import matplotlib
>>> matplotlib.use('TkAgg')
##在import matplotlib下的模組,如pyplot等之前新增上面2句
>>> import matplotlib.pyplot as plt
複製程式碼

方法二: 新增一下matplotlib的配置:

echo "backend: TkAgg" >> ~/.matplotlib/matplotlibrc
複製程式碼

然而,以上這兩種解決方式都***無法解決我的問題***,此時出現了第二個錯誤:

No module named '_tkinter'

說是找不到tkinter這個模組,找了網上大多數方法,全都是linux系統下的解決方案,我真的很好奇沒有一個使用mac的使用者出現我這樣的問題嗎? 究其原因,是因為,使用pyenv獨立安裝出來的python中並沒有tkinter這個模組,於是嘗試直接安裝tkinter,結果竟然提示沒有發現tkinter

包!

pip3 install tkinter
Collecting tkinter
Could not find a version that satisfies the requirement tkinter (from versions: )
No matching distribution found for tkinter
複製程式碼

來到這,我不禁陷入了深深的思考,這個tkinter到底是何方神聖,去了Python社群:docs.python.org/3/library/t…,這才懂了他是啥玩意:

The tkinter package (“Tk interface”) is the standard Python interface to the Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, as well as on Windows systems. (Tk itself is not part of Python; it is maintained at ActiveState.) Running python -m tkinter from the command line should open a window demonstrating a simple Tk interface, letting you know that tkinter is properly installed on your system, and also showing what version of Tcl/Tk is installed, so you can read the Tcl/Tk documentation specific to that version.

說白了,tkinter 就是一個利用python做GUI(圖形使用者介面),它提供各種標準的 GUI 介面項,以利於迅速進行高階應用程式開發。

那麼究竟去哪安裝這個tkinter包,說實話到現在我也不知道如何利用pyenv去安裝tkinter,那這個問題又該怎麼解決呢?

曲線救國

既然tkinter這個GUI庫沒用,那換個庫是不是就好了呢?結果的確和我想的一樣,在我換了一個GUI庫之後,他的確成功了。 具體操作如下: 在出現Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework.這個錯誤的時候,在終端輸入以下命令:

echo "backend : Qt5Agg" > ~/.matplotlib/matplotlibrc
複製程式碼

如果提示你沒有安裝PyQt的話,你就需要執行

brew install pyqt
複製程式碼

然後在執行

pip install PyQt5
複製程式碼

這時候在執行你的程式碼就可以了。