python module_error ai_generated true

ImportError: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running

ID: python/matplotlib-tkinter-not-available

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-09-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

matplotlib was configured to use TkAgg but the environment has no Tk installation or is running headless without DISPLAY.

generic

中文

matplotlib 被配置为使用 TkAgg,但环境未安装 Tk 或处于无头状态(无 DISPLAY)。

Workarounds

  1. 95% success
    export MPLBACKEND=Agg
    python your_script.py
  2. 82% success
    sudo apt-get install -y python3-tk tk-dev
    # then run under a real X session or Xvfb:
    xvfb-run -a python your_script.py

Dead Ends

Common approaches that don't work:

  1. 95% fail

    There is no such PyPI package; tkinter ships with the Python interpreter and needs the OS tk-dev package.

  2. 90% fail

    Reinforces the broken backend choice and fails again at import.