One possible scenario could be that Jon, Dany and their followers flee to KL and Cersei orders the gates locked.
Someone will suggest a siege, Tyrion will offer to parley with Cersei. Jon and Dany will approve. Once Tyrion is granted entrance into KL, he will negotiate with Cersei and this when the betrayal occurs. Instead of convincing Cersei to open the gates for Jon, Dany and their remaining armies and followers, Tyrion will convince Cersei (or agree with her) to keep the gates locked. This would be an almost certain death sentence for anyone outside KL. And Tyrion would be siding with his family, thinking that he could raise Cersei's baby right this time around.
In order to prevent the citizens of KL from becoming wights, Tyrion could order that they use wildfire on them, which doesn't necessarily mean the city will burn (show didn't follow all the rules about book wildfire behavior before, so...).
Meanwhile, when team Jon/Dany realise Tyrion has betrayed them, Arya can offer to show them another way into the city (the way she and Sansa got out). She could suggest a small party to sneak in and assault one gate from the inside, so that they could open it for Jon/Dany.
The NK's attack of King's Landing can happen in parallel with these events or right after Arya walks the streets littered with corpses.