python module_error ai_generated true

ImportError: Cannot load backend 'TkAgg' which requires the 'tkinter' interactive framework, as 'headless' is not running a display.

ID: python/matplotlib-agg-backend-missing

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-01-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.7 active
3.8 active

Root Cause

Running matplotlib on a headless server without a display, but the default backend (TkAgg) requires a graphical environment.

generic

中文

在无显示服务器上运行matplotlib,但默认后端(TkAgg)需要图形环境。

Workarounds

  1. 95% success Set the Agg backend before importing matplotlib.pyplot
    import matplotlib; matplotlib.use('Agg'); import matplotlib.pyplot as plt
  2. 90% success Use the 'pdf' or 'svg' backend for file output
    import matplotlib; matplotlib.use('PDF'); import matplotlib.pyplot as plt

Dead Ends

Common approaches that don't work:

  1. Installing tkinter via pip 95% fail

    tkinter is part of the standard library and cannot be installed via pip; the issue is the missing display, not the module.

  2. Setting backend after importing pyplot 90% fail

    The backend must be set before importing pyplot; setting it after has no effect.