I had the exact same problem as you with my K-r
https://www.pentaxforums.com/forums/general-technical-troubleshooting/150836-...tos-black.html
(samples deleted)
Where I would take two shots in good light and one would be ok and the other way underexposed with identical or similar settings. It would do this sometimes but not others, frustrating.
I sent it into Pentax, they kept it for awhile. Eventually they said they couldnt diagnose the issue and sent me a replacement. Maybe send it in if you can?