I am trying to remember the title of a book about a boy who learns magic. 

It was so long ago all I can remember is:

 - a young boy is being taught magic, 
 - he goes on an adventure, 
 - gets stuck in a painting,
 - in the painting is a powerful book of magic which he begins to study, 
   finds out how to get out of the painting and
 - on his way back to his village he somehow is travelling in a flying castle and pays back a man that he borrowed or stole a boat from during his journey.