Python/Python Error

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

도도걸만단 2025. 3. 3. 16:13
반응형

몇 번 마주친 이 에러,,,

Matplotlib ImportError: ‘TkAgg’ Backend Issue 해결 방법

 

오류 메시지에서 Cannot load backend 'TkAgg' 가 발생하는 이유는 서버가 GUI 환경이 없는 ‘headless’ 모드에서 실행되고 있기 때문이다.

즉, Matplotlib의 기본 백엔드(TkAgg)를 사용할 수 없어서 발생하는 문제!

 

1️⃣ 해결 방법: Matplotlib 백엔드 변경

 

matplotlib.use("Agg") 설정 추가!

import matplotlib
matplotlib.use("Agg")  # ✅ GUI 없이 사용 가능한 백엔드로 변경
import matplotlib.pyplot as plt

위 코드를 import matplotlib.pyplot as plt 전에 추가하면 해결 가능

여기에서 import matplotlib.pyplot as plt 위에 다음 코드를 추가

 

2️⃣ 실행할 때 백엔드 변경 (MPLBACKEND 환경 변수 설정)

 

만약 코드를 수정할 수 없는 경우, 터미널에서 Matplotlib 백엔드를 강제로 변경할 수도 있다

export MPLBACKEND=Agg
python /실행파일.py

이렇게 하면 실행 시 Matplotlib이 Agg 백엔드를 사용하도록 설정됨.

 

3️⃣ tkinter 설치 (권장되지 않음)

 

서버가 GUI 환경이 있는 경우라면 tkinter를 설치해서 해결할 수도 있지만, 대부분의 서버에서는 Agg 백엔드를 사용하는 게 최선의 해결책이다

 

그래도 tkinter를 설치하려면:

sudo apt-get install python3-tk

하지만 GUI 환경이 없으면 작동하지 않을 가능성이 높음.

 

반응형