painful periods are medically called dysmenorrhea. The pain comes from contraction of the uterus. Contractions if the Uterus are an effort to expel out the lining of the uterus that had formed in preparation for implantation of a foetus.
The uterus, also called the womb, is made up of a special type of muscle called smooth muscle. Smooth muscle can also be found in the intestines, and blood vessels. Smooth muscle is out of our voluntary control. You cannot control how often, how hard or how strongly such muscles contract. It is all under the control of our central nervous system.
Painful periods then will happen if the smooth muscle in the uterus contracts too strongly and for too long. It is similar to when you are running and you get a muscle pull in the large muscles of your leg. But at least this time you can choose to stop running and thus give the muscle a chance to relax.