Cause of Tkinter error when displaying matplotlib graphs using PySimpleGUI - matplotlib

I am currently developing a GUI in Python using PySimpleGUI and am working on plotting some graphs in frames contained by the main window. I succeeded in doing this using this example code1 and it looks fine. However, when I close the main window after having plotted a graph, I get the following list of errors related to Tkinter:
Exception in Tkinter callback\
Traceback (most recent call last):\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 1705, in __call__\
return self.func(*args)\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 3072, in set\
self.tk.call(self._w, 'set', first, last)\
_tkinter.TclError: invalid command name\ ".!toplevel.!frame.!notebook.!frame4.!frame4.!tkscrollableframe.!scrollbar2"\
Exception in Tkinter callback\
Traceback (most recent call last):\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 1705, in __call__\
return self.func(*args)\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 3072, in set\
self.tk.call(self._w, 'set', first, last)\
_tkinter.TclError: invalid command name\ ".!toplevel.!frame.!notebook.!frame4.!frame4.!tkscrollableframe.!scrollbar"\
Exception in Tkinter callback\
Traceback (most recent call last):\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 1705, in __call__\
return self.func(*args)\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 3072, in set\
self.tk.call(self._w, 'set', first, last)\
_tkinter.TclError: invalid command name\ ".!toplevel.!frame.!notebook.!frame4.!frame4.!tkscrollableframe.!scrollbar2"\
Exception in Tkinter callback\
Traceback (most recent call last):\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 1705, in __call__\
return self.func(*args)\
File "/usr/lib64/python3.6/tkinter/__init__.py", line 3072, in set\
self.tk.call(self._w, 'set', first, last)\
_tkinter.TclError: invalid command name\ ".!toplevel.!frame.!notebook.!frame4.!frame4.!tkscrollableframe.!scrollbar"\
I am new to matplotlib and haven't used Tkinter before, but would like to know the cause of these errors, if anyone knows. My code is quite big, but I can add it to the post if necessary.
I have tried commenting different parts of my code to find the culprit and when I remove the line corresponding to the following in the demo I used, the errors stopped:
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
Have anyone experienced this problem before? I am running this on a machine running Centos and have tried running a simpler program in Windows, which closes without any problem.
Thanks in advance.
EDIT 1: Upon request I have just added the simplest Python code I could produce that reproduces this kind of error:
import PySimpleGUI as sg
import matplotlib as mp
from matplotlib import figure
from matplotlib.backends import backend_tkagg
import numpy as np
layout1 = [
[
sg.Frame("Frame",
[
[
sg.Column(
[
[sg.Canvas(key="-CANVAS-")]
],
size=(1000,1000)
)
]
]
)
]
]
layout2 = [
[sg.Column(layout1, scrollable=True)]
]
window = sg.Window("Window", layout2)
window.finalize()
x = np.array(list(range(10)))
fig = figure.Figure()
ax = fig.add_axes((0,0,1,1))
ax.plot(x, x)
figure_canvas_tkagg = backend_tkagg.FigureCanvasTkAgg(fig, master=window["-CANVAS-"].TKCanvas)
figure_canvas_tkagg.draw()
figure_canvas_tkagg.get_tk_widget().pack()
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
window.close()
It appears that it might have something to do with the fact that my GUI code consists of many levels of container-objects within cointainer-objects. In my full code I have a couple of layers on top of this, but the error seemed to appear once I made the following hierarchy:
Column
Frame
Column
Canvas
It should be noted that using the debugger of Visual Studio Code I have found out that the error does not occur exactly when the window closes (when the window.close() method is called), but some time before.
EDIT 2: I just tested it and for some reason this error only occurs when I run the attached Python script on my Centos machine and not in Windows.
EDIT 3: I found out that if I close all the figures I have created before I close the window, these errors will not occur. This is not a complete fix however, since the error occur before the window.close() command of PySimpleGUI is run, so I don't know where to put the code that would close the figures in case the window is closed.

Related

Matplotlib.pyplot backend qt giving ValueError of image size

I am using Python 3.7. I would like to change my backend temporarily so that I can zoom in/out of my data. However, generating figures using qt backend gives me a ValueError, even if the figure is minimally simple.
Here is a minimum example, where I typed the following commands in the console one by one
[Input Commands]
import matplotlib.pyplot as plt
%matplotlib qt
plt.plot([1,2],[1,2])
[Output Error]
[<matplotlib.lines.Line2D at 0x1b2efda7648>]Traceback (most recent call last):
File "C:\Users\USER_NAME\anaconda3\lib\site-packages\matplotlib\backends\backend_qt.py", line 455, in _draw_idle
self.draw()
File "C:\Users\USER_NAME\anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py", line 431, in draw
self.renderer = self.get_renderer(cleared=True)
File "C:\Users\USER_NAME\anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py", line 447, in get_renderer
self.renderer = RendererAgg(w, h, self.figure.dpi)
File "C:\Users\USER_NAME\anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py", line 93, in __init__
self._renderer = _RendererAgg(int(width), int(height), dpi)
ValueError: Image size of 213120x159840 pixels is too large. It must be less than 2^16 in each direction.
I don't think this question is a duplicate of previous questions (here and here) because the error appears even for a very simple figure with no labels.
I thought I had accidentally overwritten some kind of setting file, so I tried re-installing matplotlib using
"conda install matplotlib" at the Anaconda prompt, but it didn't help. Changing back to my default backend "%matplotlib inline" generates figures normally.
How can I fix my qt backend?

Python Script that used to work, is now getting automatically killed in Ubuntu

I was once able to run the below python script on my Ubuntu machine without the memory errors I was getting on windows.
import pandas as pd
import numpy as np
#create a pandas dataframe for each input file
dfs1 = pd.read_csv('s1.csv', encoding='utf-8', names=list(range(0,107)),dtype='string', na_filter=False)
dfs2 = pd.read_csv('s2.csv', encoding='utf-8', names=list(range(0,107)),dtype='string', na_filter=False)
dfr = pd.read_csv('r.csv' , encoding='utf-8', names=list(range(0,107)),dtype='string', na_filter=False)
#combine them into one dataframe
dfs12r = pd.concat([dfs1, dfs2, dfr],ignore_index=True)#withour ignore index the line numbers are not adjusted
# bow is "comming
wordlist=[]
for line in range(8052):
for row in range(106) :
#print(line,row,dfs12r[row][line])
if dfs12r[row][line] not in wordlist :
wordlist.append(dfs12r[row][line])
wordlist.sort()
#print(wordlist)
print(len(wordlist)) #12350
dfBOW = pd.DataFrame(np.zeros((len(dfs12r.index), len(wordlist))),dtype='int')
#create the dictionary
wordDict = dict.fromkeys(wordlist,'default')
counter=0
for word in wordlist :
wordDict[word] = counter
counter+=1
#print(wordDict)
#will start scanning every word from dfS12R and +1 the respective cell in dfBOW
for line in range(8052):
for row in range(107):
dfBOW[wordDict[dfs12r[row][line]]][line]+=1
Unfortunately, probably after some automatic Ubuntu updates I am now getting the simple message "KIlled", after trying to run the process without any further explanation.
Through simple print statements I know that the script is interrupted inside the for loop in the end.
I understand that I should be able to make the script more memory efficient, but I am also hoping for guidance on how to get Ubuntu able to run again the same script like they used to. (Through the TOP command I can see the all of my memory including the swap is being used while inside this loop)
Could paging have been disabled somehow after the updates? Any advice is welcome.
I still have 16GB of RAM, and use Ubuntu 20.04 (Specs are the same before and after the script stopped working). I use dual boot on the same SSD.
Below is the error I am getting from teh same script on windows :
Traceback (most recent call last):
File "D:\sharedfiles\Organised\WorkSpace\ptixiaki\github\ptixiaki\code\makingthedata\2.1 Approach (Same as 2 but turning all words to lowercase)\2.1_CSVtoDataframe\CSVtoBOW.py", line 60, in <module>
dfBOW[wordDict[dfs12r[row][line]]][line]+=1
File "D:\wandowsoftware\anaconda\envs\ptixiaki\lib\site-packages\pandas\core\series.py", line 1143, in __setitem__
self._maybe_update_cacher()
File "D:\wandowsoftware\anaconda\envs\ptixiaki\lib\site-packages\pandas\core\series.py", line 1279, in _maybe_update_cacher
ref._maybe_cache_changed(cacher[0], self, inplace=inplace)
File "D:\wandowsoftware\anaconda\envs\ptixiaki\lib\site-packages\pandas\core\frame.py", line 3950, in _maybe_cache_changed
self._mgr.iset(loc, arraylike, inplace=inplace)
File "D:\wandowsoftware\anaconda\envs\ptixiaki\lib\site-packages\pandas\core\internals\managers.py", line 1141, in iset
blk.delete(blk_locs)
File "D:\wandowsoftware\anaconda\envs\ptixiaki\lib\site-packages\pandas\core\internals\blocks.py", line 388, in delete
self.values = np.delete(self.values, loc, 0) # type: ignore[arg-type]
File "<__array_function__ internals>", line 5, in delete
File "D:\wandowsoftware\anaconda\envs\ptixiaki\lib\site-packages\numpy\lib\function_base.py", line 4555, in delete
new = arr[tuple(slobj)]
MemoryError: Unable to allocate 501. MiB for an array with shape (12234, 10736) and data type int32

Keras: Error when downloading Fashion_MNIST Data

I am trying to download data from Fashion MNIST, but it produces an error. Originally, it was downloading and working properly, but I had to terminate it because I had to turn off my computer. Once I opened the file up again, it gives me an error. I'm not sure what the problem is, but is it because I already downloaded some parts of the data once, and keras doesn't recognize that? I am using Jupyter notebook in a conda environment
Here is the link to the image:
https://i.stack.imgur.com/wLGDm.png
You have missed adding tf. to the line
fashion_mnist = keras.datasets.fashion_mnist
The below code works perfectly for me. Importing the fashion_mnist dataset has been outlined in tensorflow documention here.
Change your code to:
import tensorflow as tf
fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
or, use the better way to do it below. This avoids creating an extra variable fashion_mnist:
import tensorflow as tf
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.fashion_mnist.load_data()
I am using tensorflow 1.9.0, keras 2.2.2 and python 3.6.6 on Windows 10 x64 OS.
I know my pc well, I can't download anything larger than 2.7 MB (in terminal), due to WinError 8.
So I manually downloaded all packs from storage.google (since some packs are 25 MB).
Check the packs:
then I paste all packs to \datasets\fashion-mnist
The next time u run your code, it should be fixed.
Note : If u have VScode then just CTRL and click the link, then you can download it easily.
I had an error regarding the cURL connection, and by looking into the error message I was able to track the file where the URL was declared. In my case it was:
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tensorflow_core/python/keras/datasets/fashion_mnist.py
At line 44 I have commented out the line:
# base = 'https://storage.googleapis.com/tensorflow/tf-keras-datasets/'
And declared a different base URL, which I had found looking into the documentation of the original dataset:
base = 'http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/'
The download started immediately and gave no errors. Hope this helps.
This is because for some reason you have an incomplete download for the MNIST dataset.
You will have to manually delete the downloaded folder which usually resides in ~/.keras/datasets or any path specified by you relative to this path, in your case MNIST_data.
Go to : C:\Users\Username.keras\datasets
and then Delete the Dataset that you want to redownload or has the error
You should be good to go!
You can also manually add print for the path from which it is taking dataset ..
Ex: print(paths) in file fashion_mnist.py
with gzip.open(paths[3], 'rb') as imgpath:
print(paths) #debug print in fashion_mnist.py
x_test = np.frombuffer(
imgpath.read(), np.uint8, offset=16).reshape(len(y_test), 28, 28)
& from this path, remove the files & this will start to download fresh data ..
Change The base address with 'http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/' as described previously. It works for me.
I was getting error of Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
Traceback (most recent call last):
File "C:\Users\AsadA\AppData\Local\Programs\Python\Python38\lib\site-packages\numpy\lib\npyio.py", line 448, in load
return pickle.load(fid, **pickle_kwargs)
EOFError: Ran out of input
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\AsadA\AppData\Local\Programs\Python\Python38\lib\site-packages\numpy\lib\npyio.py", line 450, in load
raise IOError(
OSError: Failed to interpret file 'C:\\Users\\AsadA\\.keras\\datasets\\mnist.npz' as a pickle"**
GO TO FILE C:\Users\AsadA\AppData\Local\Programs\Python\Python38\Lib\site-packages\tensorflow\python\keras\datasets (In my Case) and follow the instructions:

some error/warning messages for running Tensorflow implementation

When running a Tensorflow implementation, I got the following error/warning messages, which does not include the line of python code that causes this issue. At the same time, the result is still generated. I am not sure what do these messages indicate?
Exception ignored in: <bound method Session.__del__ of <tensorflow.python.client.session.Session object at 0x2b48ec89f748>>
Traceback (most recent call last):
File "/data/tfw/lib/python3.4/site- packages/tensorflow/python/client/session.py", line 140, in __del__
File "/data/tfw/lib/python3.4/site-packages/tensorflow/python/client/session.py", line 137, in close
UnboundLocalError: local variable 'status' referenced before assignment
Today I also encountered this exception while running some Multi layer perceptron model on Windows 10 64 Bit with Python 3.5 and TensorFlow 0.12
I have seen this answer for this exception
it induced by different gc sequence, if python collect session first , the program will exit successfully, if python collect swig memory(tf_session) first, the program exit with failure.
Here

Python Matplotlib errors with savefig (newbie).

All parts of Python on my computer were recently installed from the Enthought academic package, but use Pyscripter for editing and running code. I'm very early in my learning curve, and so could very well be overlooking some obvious things here.
When I try to create a plot and save it like so:
import matplotlib.pylab as pl
pl.hist(myEst, bins=20, range=(.1,.60))
pl.ylabel("Freq")
pl.xlabel("Success Probability")
pl.title('Histogram of Binomial Estimator')
pl.axis([0, 1, 0, 500])
pl.vlines (.34,0,500)
pl.savefig('TestHist.png')
pl.show()
I get these errors:
Traceback (most recent call last):
File "<editor selection>", line 9, in <module>
File "C:\Python27\lib\site-packages\matplotlib\figure.py", line 1172, in savefig
self.canvas.print_figure(*args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_wxagg.py", line 100, in print_figure
FigureCanvasAgg.print_figure(self, filename, *args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 2017, in print_figure
**kwargs)
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_agg.py", line 450, in print_png
filename_or_obj = file(filename_or_obj, 'wb')
IOError: [Errno 13] Permission denied: 'TestHist.png'
If I take out the pl.savefig('TestHist') line everything works fine, and I can see the plot I want, but when that line is in there I get the errors.
I've checked my backend version using pl.get_backend(), it returns 'WXAgg', which according to documentation should be able to use .png format.
I've also tried including an explicit format='png' and format=png within the savefig command, but still get errors.
Can anyone give me advice on how to proceed, or another approach for saving a plot?
There's nothing wrong with your code. I just tested it locally on my machine. The issue is this error:
IOError: [Errno 13] Permission denied: 'TestHist.png'
You are most likely trying to save the file somewhere that the Python process doesn't have permission to access. What OS are you on? Where are you trying to save the file?
If it helps others, I made the silly mistake of not actually designating a file name and as a result had returned the same error message that lead me to this question for review.
Here is the code that was generating the error:
plt.savefig('C:\\Users\\bwarn\\Canopy', format='png')
Here is my correction that resolved (you'll see I designated the actual file and name)
plt.savefig('C:\\Users\\bwarn\\Canopy\\myplot.png', format='png')
The following worked for me when I was running a neural network on my windows machine:
image_path = 'A:/DeepLearning/Padhai/MLFlow/images/%s.png' % (expt_id)
plt.savefig(image_path)
Or otherwise refer:
Using 'r' in front of the path