We introduce a novel approach to sample the canonical ensemble at constant temperature and applied electric potential. Our approach can be straightforwardly implemented into any density-functional theory code. Using thermopotentiostat molecular dynamics simulations allows us to compute the dielectric constant of nanoconfined water without any assumptions for the dielectric volume. Compared to the commonly used approach of calculating dielectric properties from polarization fluctuations, our thermopotentiostat technique reduces the required computational time by 2 orders of magnitude.