Bad news for you is that you can't purchase either Prague-Krakow or Krakow-Budapest tickets in advance online directly from Czech or Polish railways, so you actually got two options left - purchase tickets already in Prague and Krakow (4 days in advance is a plenty of time to do it) or use agencies. It is rather obvious from the content of this website and general idea behind - EuropeTrainsGuide team definitely would not recommend to go with second option, but it is your choice.
Since you stay 4 days in Prague and Krakow before the actual travel date, so there almost certainly will no problems purchasing tickets - those routes aren't that busy.
Prague-Krakow: no discounted tickets on this route. Regular one way ticket, as of now, costs 36.8 euro (+2 bed sleeper - 30 euro per person, 3 bed - 20 euro).
If you want to save, then you will need to do couple tricks:
a) purchase domestic Czech ticket Prague-Bohumin (since there are two of you, then you are entitled for a group discount=means you pay only 651CZK for both -
https://eshop.cd.cz/search.aspx) + international tickets Bohumin-Krakow (15 euro) to cover rest of the route to Krakow and sleeper Prague-Krakow. When boarding your Prague-Krakow train show both two tickets and sleeper reservation to the conductor.
b) take overnight train (#441, 00:24-5:09) from Prague to Cesky Tesin (check on google maps) - 704 CZK for two passengers + 280CZK per person for 3 bed sleeper or 420 for double. Cesky Tesin is located right across Polish town Cieszyn. From there you can catch frequent buses to Krakow (costs 17 PLN). Walk from C.Tesin train station to Cieszyn bus station takes app.15 minutes
Concerning Krakow-Budapest overnight train ride there was just recently a discussion, so check it out -
http://europetrainsguide.com/forum/index.php/topic,57.0.html and if you have any questions - feel free to ask. And just one more thing to add - during summer there will be additional and cheaper overnight train from Warsaw-Krakow to Budapest via Kosice, so more chances to travel.
Budapest-Ljubljana can be easily done by afternoon-evening train (2:11pm-11:05pm), no seat reservations required, so don't worry about seats. One way ticket costs on 29 euro, it can be purchased any time from any ticket counters in Budapest.
Ljubljana-Zagreb as well easy thing to accomplish, multiple trains, fare is 13 euro one way.