First of all, there's no such thing as a safe 40kV power supply. Second, I can't imagine a way to control the voltage smoothly at such high voltages without huge power dissipation. You could, however, use a Cockcroft-Walton generator and simply select your voltage from the different stages.
http://en.wikipedia.org/wiki/Cockcroft-Walton_generatorIf you don't mind using a ton of components, you could start off with an isolation transformer from the wall. Your output would be multiples of 170V with the steps sagging down as the voltage gets higher due to impedance. If you wanna use fewer components, you could run it off of an already hgih voltage source, such as a microwave oven transformer, flyback transformer, neon sign transformer, ignition coil autotransformer, high voltage inverter circuit, etc.. That way, your steps would be the peak voltage of your transformer. The most ideal would be the inverter or an inverter with a transformer output because you can set the frequency. Higher frequencies lead to less output voltage ripple.
The main issue with creating voltages this high is obtaining high voltage components with large enough values. You could always put lower-voltage components in series, but then you might also have to add additional strings in parallel to increase the values and/or current handling. The beauty of a Cockcroft-Walton generator is that the maximum voltage any component sees is twice the peak voltage of your input voltage source.
Other issues involve power dissipation, arcing from inadequate insulation, and corona discharge. Power dissipation can be reduce by reducing ESR wherever possible. Arcing can be reduced with heavier insulation and larger spacing between components. Corona can be reduced by smoothing any sharp edges and adding insulation.
High voltage is not something you can figure out in a day. Especially voltages as high as 40kV. Good luck with your project. I'd look into the possibility of a Cockcroft-Walton generator.