Matplotlib 缺少 tkinter
Original...About 1 min
Matplotlib 缺少 tkinter
装了新版 Python 后使用 matplotlib 出现了这样的问题:
****.py: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
plt.show()
根据报错信息,使用了无 GUI 的后端。
搜索相关问题,看到有人给出解决方案:
import matplotlib
matplotlib.use('TkAgg')
但是这样操作会导致新的运行时报错:
Traceback (most recent call last):
File "****.py", line 40, in <module>
plt.figure(figsize=(12, 4))
File "D:\Program Files\Python\Python311\Lib\site-packages\matplotlib\_api\deprecation.py", line 454, in wrapper
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "D:\Program Files\Python\Python311\Lib\site-packages\matplotlib\pyplot.py", line 840, in figure
manager = new_figure_manager(
^^^^^^^^^^^^^^^^^^^
File "D:\Program Files\Python\Python311\Lib\site-packages\matplotlib\pyplot.py", line 383, in new_figure_manager
_warn_if_gui_out_of_main_thread()
File "D:\Program Files\Python\Python311\Lib\site-packages\matplotlib\pyplot.py", line 361, in _warn_if_gui_out_of_main_thread
if _get_required_interactive_framework(_get_backend_mod()):
^^^^^^^^^^^^^^^^^^
File "D:\Program Files\Python\Python311\Lib\site-packages\matplotlib\pyplot.py", line 208, in _get_backend_mod
switch_backend(rcParams._get("backend"))
File "D:\Program Files\Python\Python311\Lib\site-packages\matplotlib\pyplot.py", line 271, in switch_backend
backend_mod = importlib.import_module(
^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Program Files\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "D:\Program Files\Python\Python311\Lib\site-packages\matplotlib\backends\backend_tkagg.py", line 1, in <module>
from . import _backend_tk
File "D:\Program Files\Python\Python311\Lib\site-packages\matplotlib\backends\_backend_tk.py", line 8, in <module>
import tkinter as tk
ModuleNotFoundError: No module named 'tkinter'
结论:没有 tkinter
模块,因此无法使用对应的 GUI 后端。但 tkinter
不是扩展包,而是内置包。
其实是因为安装时没加 Tcl/Tk Support
,执行安装包 modify 一下就行了。
问题解决。