-1

I am working with pycharm community on a tensorflow model with keras backend, sometimes this error appears in a random time, specially after I call pyplot and close the window:

Exception ignored in: <bound method Image.__del__ of <tkinter.PhotoImage object at 0x7ff6406fad30>>
Traceback (most recent call last):
  File "/usr/lib/python3.6/tkinter/__init__.py", line 3507, in __del__
    self.tk.call('image', 'delete', self.name)
    RuntimeError: main thread is not in main loop

After this error, I need to close the python console and load my data again which is time-consuming (the data is a big dataset and the memory usage is considerable)

How do I resolve this problem?

UPDATE: Here is the plot code:

import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
import numpy as np

data = np.ones((256,256))
fig = plt.figure()
ax = fig.add_subplot(111)
temp = np.transpose(data)
plt.title('title')
im = ax.imshow((temp), aspect='auto')
fig.colorbar(im)
plt.axes()

data2 = np.ones((256,256))
fig = plt.figure()
ax = fig.add_subplot(111)
temp = np.transpose(data2)
plt.title('title')
im = ax.imshow((temp), aspect='auto')
fig.colorbar(im)
plt.axes()

UPDATE 2:

I have PyCharm 2021.2.3(Community Edition)

build PC-212.5457.59
Runtime version: 11.0.12+7-b1504.40 amd64

I have the following packages installed:

Package                 Version            
----------------------- -------------------
absl-py                 0.9.0              
appdirs                 1.4.3              
apturl                  0.5.2              
asn1crypto              0.24.0             
astor                   0.8.1              
bleach                  2.1.2              
Brlapi                  0.6.6              
certifi                 2018.1.18          
chardet                 3.0.4              
command-not-found       0.3                
control                 0.9.0              
cryptography            2.1.4              
cupshelpers             1.0                
cycler                  0.10.0             
decorator               4.4.2              
defer                   1.0.6              
distlib                 0.3.0              
distro-info             0.18ubuntu0.18.04.1
entrypoints             0.2.3.post1        
filelock                3.0.12             
gast                    0.2.2              
google-pasta            0.1.8              
graphviz                0.14               
grpcio                  1.27.2             
h5py                    2.10.0             
html5lib                0.999999999        
httplib2                0.9.2              
idna                    2.6                
imageio                 2.9.0              
imageio-ffmpeg          0.4.3              
imgviz                  1.2.5              
importlib-metadata      1.5.0              
importlib-resources     1.3.1              
ipykernel               4.8.2              
ipython                 5.5.0              
ipython-genutils        0.2.0              
ipywidgets              6.0.0              
Jinja2                  2.10               
joblib                  0.14.1             
jsonschema              2.6.0              
jupyter-client          5.2.2              
jupyter-core            4.4.0              
Keras                   2.4.3              
Keras-Applications      1.0.8              
Keras-Preprocessing     1.1.0              
keyring                 10.6.0             
keyrings.alt            3.0                
kiwisolver              1.1.0              
labelme                 4.5.7              
language-selector       0.1                
launchpadlib            1.10.6             
lazr.restfulclient      0.13.5             
lazr.uri                1.0.3              
llvmlite                0.34.0             
louis                   3.5.0              
macaroonbakery          1.1.3              
Markdown                3.2.1              
MarkupSafe              1.0                
matplotlib              3.0.3              
mistune                 0.8.3              
moviepy                 1.0.3              
nbconvert               5.3.1              
nbformat                4.4.0              
netifaces               0.10.4             
networkx                2.5.1              
notebook                5.2.2              
numba                   0.51.2             
numpy                   1.19.5             
oauth                   1.0.1              
olefile                 0.45.1             
opt-einsum              3.2.0              
pandas                  1.0.4              
pandocfilters           1.4.2              
pexpect                 4.2.1              
pickleshare             0.7.4              
Pillow                  5.1.0              
pip                     20.0.2             
proglog                 0.1.9              
prompt-toolkit          1.0.15             
protobuf                3.11.3             
pycairo                 1.16.2             
pycrypto                2.6.1              
pycups                  1.9.73             
pydot                   1.4.1              
pydot-ng                2.0.0              
pydotplus               2.0.2              
Pygments                2.2.0              
pygobject               3.26.1             
pymacaroons             0.13.0             
PyNaCl                  1.1.2              
pyparsing               2.4.6              
pyRFC3339               1.0                
python-apt              1.6.5+ubuntu0.5    
python-dateutil         2.6.1              
python-debian           0.1.32             
pytz                    2018.3             
PyWavelets              1.1.1              
pyxdg                   0.25               
PyYAML                  3.12               
pyzmq                   16.0.2             
QtPy                    1.9.0              
reportlab               3.4.0              
requests                2.18.4             
requests-unixsocket     0.1.5              
scikit-image            0.17.2             
scikit-learn            0.22.2.post1       
scipy                   1.4.1              
screen-resolution-extra 0.0.0              
seaborn                 0.11.0             
SecretStorage           2.3.1              
setuptools              46.0.0             
simplegeneric           0.8.1              
simplejson              3.13.2             
six                     1.14.0             
sklearn                 0.0                
system-service          0.3                
systemd-python          234                
tensorboard             1.14.0             
tensorflow-estimator    1.14.0             
tensorflow-gpu          1.14.0             
termcolor               1.1.0              
terminado               0.7                
testpath                0.3.1              
tifffile                2020.9.3           
tornado                 4.5.3              
tqdm                    4.56.2             
traitlets               4.3.2              
ubuntu-drivers-common   0.0.0              
ufw                     0.36               
unattended-upgrades     0.1                
urllib3                 1.22               
virtualenv              20.0.10            
wadllib                 1.3.2              
wcwidth                 0.1.7              
webencodings            0.5                
Werkzeug                1.0.0              
wheel                   0.34.2             
wrapt                   1.12.1             
xkit                    0.0.0              
zipp                    3.1.0              
zope.interface          4.3.2  
Farnaz
  • 534
  • 11
  • 28
  • 2
    show code which makes this problem. It is not problem with `PyCharm` but with your code. It seems you run `tkinter` in two `threads` but most `GUIs` don't like to run in theads. Probably when you close window then it destroy it but other thread is still running and it tries to display image in window which was destroyed. you have to stop threads before destroying main window in tkinter. – furas Nov 22 '21 at 11:34
  • This looks like it could be related: https://stackoverflow.com/questions/50848127/python-plot-image-save-error – Shaido Nov 25 '21 at 08:20
  • Thanks for the hint, but that solution did not work for me. – Farnaz Nov 25 '21 at 08:37
  • https://stackoverflow.com/questions/14694408/runtimeerror-main-thread-is-not-in-main-loop it seems like this – prof_FL Nov 27 '21 at 05:14
  • 1
    I believe the problem is connected to Tk/Pycharm interaction and is not related to tensorflow or keras. Try changing matplotlib backend (change argument to matplotlib.use() command to 'WXAgg' or 'Qt5Agg') to wxPython or PyQt (you will need to install the frameworks) – igrinis Nov 30 '21 at 13:55

1 Answers1

1

Looks like this is part of an actively tracked issue with Tkinter in PyCharm. You can find the reference on the Pycharm's developer's issue tracker. The issue is undiagnosed, but if looking at similar problems with Tk on StackOverflow, one can see that it's an issue with thread safety and/or multithreading.

All I can do is speculate as to the cause, which is not helpful, however, I can at least collate the suggested workarounds:

  1. Switch to a different Matplotlib backend (See docs: What is a backend?). Such as Qt5, but you will need to make sure they are available in your environment.

    This approach is the most promising as other backends are better able to deal with not being the main thread or are explicitly safe for multi-threading. It's also the simplest unless you have a really specific reason for preferring TkAgg.

  2. Do not use the debugger with interactive plots.

  3. Set "Variables Loading Policy" to "Synchronously" in Debugger as suggested by a PyCharm dev in the linked issue.

  4. Enable "Scientific mode" in Pycharm.

  5. More esoteric workarounds such as closing your figures within the code before drawing the second one. Example, after plotting the first figure:

       # Save out figure if desired, then close
       # Assuming not using a blocking draw/show call.
       fig.savefig('myfig.png')
       plt.close() #  Object oriented: fig.close()
    

As per speculation to the cause, maybe PyCharm's debugger is kicking Tk off the main thread or runs it in a worker thread that is closed while the figure is still active or rendered.

Finally, please also take a look at the relevant documentation for Matplotlib, as your code example does not follow their recommended usage patterns. Specifically, learn about the differences between object oriented and the pyplot approach from the link. Possibly, somewhat unlikely, if the code stuck to recommended ways of using Matplotlib as highlighted in their tutorial documents, the error might not appear. This is just speculation.

I would at least recommend not misusing plt.axes() as a roundabout way of forcing a render of your figure. You already create an axes using the object oriented approach fig.add_subplot, so you do not need to create an empty axes with pyplot. Recall that figures can be memory heavy, so, if you are memory starved already from loading your dataset, you may find better performance and avoid using the swap by properly dealing with your figures such as closing them when done, not rendering them interactively unless needed, etc.

Emir
  • 373
  • 1
  • 6