WASHINGTON — During his surprise visit to American troops in Iraq and Germany this week, President Trump singled out red “Make America Great Again” caps in a sea of military fatigues, signed a “Trump 2020” patch and accused Representative Nancy Pelosi and other leading Democrats of being weak on border security.

Now the president is facing accusations that he was playing politics with the military.

“When that starts happening, it’s like the politicalization of the judicial branch,” said Mark Hertling, a retired three-star Army lieutenant general.

Visiting troops abroad is a presidential tradition in which the commander in chief puts aside politics to thank a military that represents a broad spectrum of the country. But Mr. Trump’s political comments and his encouragement of supporters in the crowd veered from those norms.

“He has to understand that there exist some audiences that should not be addressed as part of his base, because they are not,” Mr. Hertling said. “It’s a violation of protocol by the president.”