Minesweeper, python Tkinter, Checking close by tiles Is there any smart way to compress the following code:

def __total(self, x, y):
    count = 0
    for x_offset in range(-1, 2):
        x_index = x + x_offset
        for y_offset in range(-1, 2):
            y_index = y + y_offset
            if 0 &lt;= x_index &lt; self.Size and 0 &lt;= y_index &lt; self.__Size:
                count += self.__buttons[y_index][x_index].mine
    if not count:
        for x_offset in range(-1, 2):
            x_index = x + x_offset
            for y_offset in range(-1, 2):
                y_index = y + y_offset
                if 0 &lt;= x_index &lt; self.__Size and 0 &lt;= y_index &lt; self.__Size:
                    self.__push(x_index, y_index)
    return count


I have been trying forever with an extreme "coder-blackout" not being able to succeed....
Okay. Improved my answer. You can call this code as normal with self.__total(x,y). In my own test, it showed the exact same results as your code has. 

def __total(self, x, y, count=0, old=False):
    if (not count and old) or not old:
        for x_index in range(-1+x, 2+x):
            for y_index in range(-1+y, 2+y):
                if 0 &lt;= x_index &lt; self.__Size and 0 &lt;= y_index &lt; self.__Size:
                    if old:
                        self.__push(x_index, y_index)
                    else:
                        count += self.__buttons[y_index][x_index].mine

    if old:
        return count
    return self.__total(x,y, count, True)


Another solution would be using Numpy:

import numpy as np

def __total(self, x,y):
    count = np.sum( self.__buttons[ x-1 if x&gt;0 else 0:x+2, y-1 if y&gt;0 else 0:y+2 ] )
    if not count:
        for x_offset in range(-1, 2):
            x_index = x + x_offset
            for y_offset in range(-1, 2):
                y_index = y + y_offset
                if 0 &lt;= x_index &lt; self.__Size and 0 &lt;= y_index &lt; self.__Size:
                    self.__push(x_index, y_index)
    return count


The problem with this code is, that you can't use array class, but would need a Numpy array of all mines in a extra variable. But it would speed up your calculations just because of the nature of Numpy.