It may seem like a simple thing to lock the transmission and keep it from spinning, but there are actually some complex requirements for this mechanism. First, you have to be able to disengage it when the car is on a hill (the weight of the car is resting on the mechanism). Second, you have to be able to engage the mechanism even if the lever does not line up with the gear. Third, once engaged, something has to prevent the lever from popping up and disengaging.
The mechanism that does all this is pretty neat. Let's look at some of the parts first.
The parking-brake mechanism engages the teeth on the output to hold the car still. This is the section of the transmission that hooks up to the drive shaft -- so if this part can't spin, the car can't move.
Above you see the parking mechanism protruding into the housing where the gears are located. Notice that it has tapered sides. This helps to disengage the parking brake when you are parked on a hill -- the force from the weight of the car helps to push the parking mechanism out of place because of the angle of the taper.
This rod is connected to a cable that is operated by the shift lever in your car.
When the shift lever is placed in park, the rod pushes the spring against the small tapered bushing. If the park mechanism is lined up so that it can drop into one of the notches in the output gear section, the tapered bushing will push the mechanism down. If the mechanism is lined up on one of the high spots on the output, then the spring will push on the tapered bushing, but the lever will not lock into place until the car rolls a little and the teeth line up properly. This is why sometimes your car moves a little bit after you put it in park and release the brake pedal -- it has to roll a little for the teeth to line up to where the parking mechanism can drop into place.
Once the car is safely in park, the bushing holds down the lever so that the car will not pop out of park if it is on a hill.