Do you pay a tourist visa fee for each country you go through on the train, or do you pay only if you leave the train?
In almost every case it will be the first option. If, due to your citizenship, you need a visa to enter a country you will be forced to get at least a transit visa and it doesn't matter whether you leave the train or not. In such cases you undergo full scale border crossing procedure.
Usually visa is not needed only in cases when a train passes small part of the other countries territory and does it without any stops, like Bar-Belgrade trains pass 9km part of BiH or trains from Austria nonstop pass couple km of Liechtenstein's territory on their way to Switzerland.