Pakistan’s two main political dynasties reached an agreement late on Tuesday to form a coalition government, ensuring that candidates aligned with former Prime Minister Imran Khan will not take power despite having won the most seats in last week’s election.

Leaders of the party favored by the country’s powerful military, the Pakistan Muslim League-Nawaz, or P.M.L.N., announced that they had joined forces with another major party, the Pakistan People’s Party, and others to reach a two-thirds majority in the incoming Parliament.

“This is not a time for disagreements, but to unite,” said Shehbaz Sharif, a former prime minister whom the coalition said it would nominate to regain that post. “Let’s move forward, move the economy forward, end mutual differences.”

The announcement came five days after a national election that most had expected P.M.L.N. to win easily after it received the backing of the military, which has frequently engineered electoral outcomes. In a stunning upset, candidates allied with Mr. Khan routed the two longstanding major parties, defying a monthslong military crackdown on their own party and delivering a sharp rebuke to the country’s generals.

The election results set off days of political jockeying. As P.M.L.N. and the P.P.P. discussed joining forces, the country waited to see if Mr. Khan, who is serving multiple jail sentences on charges he says are politically motivated, could pull off another upset and form a coalition of his own.

While Tuesday’s announcement confirms that members of Mr. Khan’s party, Pakistan Tehreek-e-Insaf, or P.T.I., will sit in the opposition in Parliament, they will be far from sidelined, potentially posing a serious challenge to the coalition government.