Simplistically, when an atom is in the flame, i.e., it receives more energy, an electron in the outer shell of that atom jumps up to a higher shell position. This electron then falls back to is original position and in doing so emits a photon of light of a specific energy. We see this light as the colour of a specific wavelength. Atoms from different elements have different numbers of electrons in their electron shells, so the photons emitted as these electrons jump back, have different energy levels. Therefore, they emit light of a different wavelength/colour.