Variational calculation of electromagnetic instabilities in tokamaks