Question: In a Parliamentary democracy, general elections appoint constituency representatives. Most such appointees are members of parties with internally determined leaders. One or more parties then form a government, with one of these party leaders the head of government.

However, it's theoretically possible that a party that enters or stays in government due to its electoral performance has to change leader, due to that individual losing their seat. (Party leaders typically come from safe seats to prevent this.)

Has this ever actually happened? I'd be interested if this happened in the UK, or failing that in any nation with a Westminster system.

Answer: 
You could make the case that this "almost" happened to the Scottish National Party in the recent UK general election, and the situation would have been even closer to the OP's criterion if the SNP had become part of a coalition government.

The SNP remains the party with the largest number of Westminster MPs in Scotland (though reduced from 53 to 35 MPs in the 2017 election), but its former leader in Westminster, Angus Robertson, lost his seat to the Conservative candidate. The former party leader, Alex Salmond, also lost his Westminster seat. 

Note, the current SNP party leader (Nicola Sturgeon) is an MSP in the Scottish Parliament, not at Westminster, and was therefore not a candidate in the Westminster election.
In the US, Tom Foley was Speaker of the House and lost his race for reelection in 1994. However, his party also lost (so he would not have been Speaker if he had won). 

More directly, Galusha A. Grow lost his bid for reelection in 1862. His party (Republicans) kept the House and he was replaced by another Republican, Schuyler Colfax. 

Grow had replaced William Pennington as Speaker after Pennington lost his seat.