プログラムを中心とした個人的なメモ用のブログです。 タイトルは迷走中。
内容の保証はできませんのであしからずご了承ください。

2020/03/07

[Python] matplotlib で plot する際に "Tcl_AsyncDelete: async handler deleted by the wrong thread" というエラーがでる

update2022/04/01 event_note2020/03/07 2:22

matplotlib を使って画像を作成する場合に、たまに以下のようなエラーが表示されます。

エラー内容

Exception ignored in: <function Image.__del__ at 0x000002ABF39B1310>
Traceback (most recent call last):
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 4014, in __del__
    self.tk.call('image', 'delete', self.name)
RuntimeError: main thread is not in main loop
Exception ignored in: <function Image.__del__ at 0x000002ABF39B1310>
Traceback (most recent call last):
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 4014, in __del__
    self.tk.call('image', 'delete', self.name)
RuntimeError: main thread is not in main loop
Exception ignored in: <function Image.__del__ at 0x000002ABF39B1310>
Traceback (most recent call last):
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 4014, in __del__
    self.tk.call('image', 'delete', self.name)
RuntimeError: main thread is not in main loop
Exception ignored in: <function Image.__del__ at 0x000002ABF39B1310>
Traceback (most recent call last):
  File "C:\Users\username\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 4014, in __del__
    self.tk.call('image', 'delete', self.name)
RuntimeError: main thread is not in main loop
Tcl_AsyncDelete: async handler deleted by the wrong thread

ググってみたところ、matplotlib.use('Agg') を追加すればよいそうなので、以下のようにして追加しました。

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

とりあえず今のところ、このエラーは表示されなくなりました。