Why does a bubble take a spherical shape?

Rising bubbles of air in a liquid oftentimes are anything but spherical.

These bubbles have haphazard shapes because they are rising and because they are interacting with other nearby bubbles. The combination of drag, turbulence, and mutual interactions prevents those bubbles from taking on a nice, simple spherical shape.

Here's a rather non-spherical giant-sized soap bubble:

The extreme size of the bubble and gravity get in the way of the bubble taking on a nice, simple spherical shape.

You're probably asking about bubbles like this one:

This bubble is isolated, is more or less stationary, is more or less the same density as the surrounding air, isn't that large, and lives for a long enough time to relax to that nearly spherical shape.

Why a sphere? A sphere is the unique geometrical shape that minimizes the surface area given an object of a fixed volume. The reason this is the preferred shape is entropy. Minimizing the surface area minimizes the potential energy of the bubble, and that in turn maximizes entropy. See Why does a system try to minimize potential energy? for details.

For the sake of the explanation I will assume you mean a gas bubble in a liquid*.

David Hammen names a few conditions for a bubble to be spherical, in fact you could summarize these all as: for a bubble to be spherical the surface tension has to dominate over other forces (per unit length).

If surface tension is indeed dominant than the pressure in the gas bubble is meanly determined by the Laplace pressure jump across the bubble interface, $\Delta P_c$. This pressure consists of two terms: the surface tension between the gas and the liquid, $\gamma$ and the local curvature of the interface, $\kappa$, which is usually written as the sum of the inverse of two principle radii of curvature like this: $$\Delta P_c = \gamma \left(\frac{1}{R_1}+\frac{1}{R_2}\right) $$

When we look for an equilibrium situation, still in the case where surface tension is dominant, we are looking for a situation in which the pressure in the bubble is equal everywhere. If that is not the case we get a flow from one place to the other. This means that we are looking for a situation where $\Delta P_c$ is constant on the entire interface of the bubble. The only way this can happen is if $\left(\frac{1}{R_1}+\frac{1}{R_2}\right)$ is constant all over the interface, i.e. constant mean curvature. A sphere is the only closed shape for which this is the case, hence explaining why a gas bubble evolves towards a spherical shape in the absence of other forces.

*The logic applies to the soap bubbles in the other answers as well, but soap bubbles are in fact a bit more complicated