A pilot is allowed to leave the cockpit, but only for the minimum amounts of time, like to use the bathroom. Lots of pilots will try to limit themselves when it comes to drinking liquids to avoid having to leave the cockpit too often. They are able to leave the cockpit if they need to, but the rules of doing so will vary depending on the airline. In the US, a flight attendant will need to take the pilot’s place in the cockpit when they leave.
The rules are slightly different according to the German aviation safety authority, where it is dictated that when there are two crew, one of them can leave the cockpit, but only for the absolute minimum time.
Other airlines have a rule of two, so if one pilot leaves the cockpit, another member of the crew must take their place while they’re gone.